data integrity when interrupts are too fast I have an encoder that fires ~54000 interruptions per second.
This is way too fast for my arduino uno.
But I'm trying to see what I can get from it anyway. For science.

unsigned long tickACount = 0;
unsigned long tickBCount = 0;

void myInterrupt(){
  tickACount++;
  tickBCount++;
}

Then in my main loop, every second I print tickACount and tickBCount.
I can see my arduino is able to handle only about 2050 interrupts per second. No surprise here.

What surprises me, is that tickACount and tickBCount have different values! tickBCount is consistently higher that tickACount.

Ok now I switch them to volatile. And according to the documentation, volatile only makes sense for 8bit values. The counts will eventually overflow but it doesn't really matter. I just want to see if those two variables are still different.

volatile uint8 tickACount = 0;
volatile uint8 tickBCount = 0;

void myInterrupt(){
  tickACount++;
  tickBCount++;
}

The result is that the two values are still different.
Also, wrapping them into some ATOMIC macro does not help.

From what I read, interrupts cannot be interrupted.
And beside, if my interrupt was aborted midway, then tickACount would be higher than tickBCount, not the other way around.

Therefore, what can be the explanation for those two variables to be different?

Thank you for any idea!

54000 interruptions per second [...] is way too fast for my arduino
  uno

Your test is probably flawed. My Uno does handle that interrupt rate
with no issues. See my test code below.

  my arduino is able to handle only about 2050 interrupts per second

You are probably doing something wrong, like blocking interrupts for too
long, or using a library that does so.

  What surprises me, is that tickACount and tickBCount have
  different values!

As previously stated in comments, this is not the case. Instead, the
counters have been incremented while you were printing them.

  And according to the documentation, volatile only makes sense for 8bit
  values.

Either the documentation is grossly wrong, or (most likely) you have
misread it.

  From what I read, interrupts cannot be interrupted.

This is indeed the default behavior. You could change it, by issuing
interrupts() within the interrupt handler, or by declaring an ISR as

ISR(XXX_vect, ISR_NOBLOCK)
{
    ...
}

but that is seldom done.

Below is my test code. I used Timer 2 to generate a square wave on
pin 3, which is both a PWM pin (OC2B) and an interrupt pin (INT1).
The PWM frequency is about 54.054 kHz.

const uint32_t PRINT_PERIOD = 1e6;  // print counts every second

struct TickCounts {
    uint32_t tickA;
    uint32_t tickB;
};

volatile TickCounts rawCounts;

void myInterrupt() {
    rawCounts.tickA++;
    rawCounts.tickB++;
}

// Atomically read both counts.
static TickCounts getCounts() {
    TickCounts counts;
    noInterrupts();
    counts.tickA = rawCounts.tickA;
    counts.tickB = rawCounts.tickB;
    interrupts();
    return counts;
}

void setup() {
    // PWM at 54 kHz on OC2B = PD3 = INT1
    DDRD  |= _BV(PD3);    // pin PD3 as output
    OCR2A  = 37 - 1;      // period = 37 * 0.5 us = 18.5 us
    OCR2B  = 37/2 - 1;    // duty cycle ~ 50%
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS21);   // clock at F_CPU/8 = 2 MHz

    Serial.begin(9600);
    attachInterrupt(1, myInterrupt, RISING);
}

void loop() {
    static uint32_t last_time_printed;
    if (micros() - last_time_printed >= PRINT_PERIOD) {
        last_time_printed += PRINT_PERIOD;
        TickCounts counts = getCounts();
        Serial.print(counts.tickA);
        Serial.print(" ");
        Serial.println(counts.tickB);
    }
}

And here is the output:

54053 54053
108107 108107
162161 162161
216215 216215
270269 270269
324324 324324
378377 378377
432431 432431
486485 486485
540539 540539
...


Using a button to toggle an LED ON/OFF I'm fairly new to Arduino and am trying to use a push button to toggle an LED on and off using a momentary press of the button. This code is lifted straight off the tutorial on the Arduino website but is not working for me. It seems to send the LED on a loop - switching between on and off by itself, and pressing the button pauses the cycle.

Any ideas as to why it is doing that?

int buttonPin = 2;         // the number of the input pin
int ledPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

void setup()
{
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);

}

void loop()
{

  reading = digitalRead(buttonPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
if (reading == HIGH  && previous == LOW && millis() - time > debounce) {
  if (state == HIGH)
    state = LOW;
  else
    state = HIGH;
time = millis();
}

else
  if (state == LOW)
    state = LOW;
  else
    state = HIGH;
  digitalWrite(ledPin, state);
 //Serial.println(buttonPin);
  //
 Serial.println(reading);
previous = reading;
}

I tested your sketch and it works. I simplified it; it's the same logic, but in a more concise way:

void loop()
{
    reading = digitalRead(buttonPin);

    // if the input just went from LOW and HIGH and we've waited long enough
    // to ignore any noise on the circuit, toggle the output pin and remember
    // the time
    if(reading == HIGH  && previous == LOW && millis() - time > debounce) {
        state = !state;
        time = millis();
    }

    digitalWrite(ledPin, state);
    Serial.println(reading);
    previous = reading;
}

setup is still the same.


Is there a way to upload precompiled code to an arduino? My company is developing a programmable remote control car which is driven by an Arduino Nano. We would like a way for the user to install software updates to the Arduino, but we don't want to give the user access to the code.

Is there a way to compile Arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?

Then after this how would I go about manually uploading it (to the Arduino)?

Is there a way to compile arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?

Yes, you can save the .hex file produced by the compiler. If you turn on verbose output from the compiler you can find the temporary directory where it is stored. Simply copy from there to a folder for download on the website.

  And then after this how would I go about manually uploading it (To the arduino)?

You can do that with the command line tool avrdude but as that is somewhat complex with a lot of parameters it might be easier to use a graphical front-end. One such tool is xloader. There are several. This depends on your end-users and the host machine that they will be using.

You can find some more info here.

Cheers!


What is the necessity of “Prototyping Shield” for an arduino UNO R3? I just want to learn arduino and make some small projects.But in beginner starter kit there's a part named Prototyping Shield .Is it necessary or will it help me?

The prototyping shield can be used to build your own circuits up in a more permanent form which can be plugged direct into the Arduino.

You can think of it as a blank canvass on which you can paint your own shield design.


Information about 'Arduino Nano 33 IoT' blox w-102 is based on esp32** which (Esp32) can be used as a standalone chip for projects.
Here I want to know how w-102 and samd21g18a are communicating with each other.
If they are communicating then what is the need of doing so?

The Arduino boards with the NINA module: MKR 1010 WiFi, MKR 4000 vidor, Uno WiFi and Nano 33 IoT use the NINA module for WiFi networking with the WiFiNINA library and for BLE with the ArdunioBLE library. Additionally the flash memory of the NINA module will be available as storage.

The NINA module runs a firmware made by Arduino with ESP32 IDF framework.

I wired MKR ZERO with an ESP32 dev board for the WiFiNINA firmware and library according to MKR 1010 WiFi schematics, which is very similar to Nano 33 IoT. The MCUs are connected on SPI pins and UART for communication. The firmware uses one additional pin to signal to SPI master as 'ready' pin. Also io 0 and enable pin of NINA module are wired to put the ESP32 into flashing mode for firmware upgrade over UART.

On MKR 1010 and Nano33 IoT I2C is connected too. Boot MCU have access to on-board I2C sensors and could in theory communicate over I2C. This is currently not used.

The WiFiNINA library uses SPI communication. SAMD is master, NINA is slave.

The ArduinoBLE library communicates over UART. 'Ready' pin is used to switch to BLE mode in firmware at NINA reset.

The firmware uses io 0 as 'heartbeat' signal for the library.

My wiring:

the orange wire from MKR pin 5 is connected as reset to EN (with a wire under the ESP32 board)
io 0 of ESP32 is the yellow wire to MKR pin 4
VSPI pins 5, 18, 19, 23 (I changed 12 to 19 in firmware). white wire on MKR pin 7 and ESP32 pin 19 is CS
I used 22 as readyPin (originally 33). white wire on MKR pin 6
I didn't wire I2C and Serial here


Arduino Web Server and Relay Module I am working on a web server project for work. I have a web server setup with an Arduino Meg2560 with Ethernet. I also have a 16 relay board connected to Ethernet with its own IP. I wanted to see if there is a way I can make calls to the relay board via IP from the Arduino Webserver. For example Relay 1 on the relay board can be turned on by typing 192.168.1.4/30000/00 but this opens the web GUI on the board. I need to do the same thing but without opening the webpage or web GUI.

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

    // MAC address from Ethernet shield sticker under board
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 177); // IP address
    EthernetServer server(80);  // Server Port 80

    void setup()
    {
      Ethernet.begin(mac, ip);
      server.begin();
    }

    void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
        if (client.available()) {   // client data available to read
            char c = client.read(); // read 1 byte (character) from client
            // last line of client request is blank and ends with \n
            // respond to client only after last line received
            if (c == '\n' && currentLineIsBlank) {
                // send a standard http response header
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println("Connection: close");
                client.println();
                // send web page
                client.println("<!DOCTYPE html>");
                client.println("");
                client.println("");
                client.println("<title>Arduino Web Page</title>");
                client.println("");
                client.println("");
                client.println("
Hello from Arduino!
");
                client.println("
A web page from the Arduino server
");
                client.println("");
                client.println("");
                break;
            }
            // every line of text received from the client ends with \r\n
            if (c == '\n') {
                // last character on line of received text
                // starting new line with next character read
                currentLineIsBlank = true;
            }
            else if (c != '\r') {
                // a text character was received from client
                currentLineIsBlank = false;
            }
        } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
} // end if (client)

}

Documentation on the controller you are using is pretty scant, but it looks like you just need to make a GET request to the URI corresponding to the action you need to take.

  http://192.168.1.4/30000/00 : Relay-01 OFF

  http://192.168.1.4/30000/01 : Relay-01 ON

  http://192.168.1.4/30000/02 : Relay-02 OFF

  http://192.168.1.4/30000/03 : Relay-02 ON

  http://192.168.1.4/30000/04 : Relay-03 OFF

  http://192.168.1.4/30000/05 : Relay-03 ON

  …

  http://192.168.1.4/30000/14 : Relay-8 OFF

  http://192.168.1.4/30000/15 : Relay-8 ON

  http://192.168.1.4/30000/41 : Enter

  http://192.168.1.4/30000/40 : Exit

  http://192.168.1.4/30000/42 : Next Page

  http://192.168.1.4/30000/43 : Next Page

For example If I wanted to turn off relay 3, I would simple make a GET request to http://192.168.1.4/30000/04 and close the connection. Example code:

IPAddress server(192,168,1,4);
EthernetClient client;
client.connect(server, 80);
client.println("GET /30000/04 HTTP/1.1");
client.println("Connection: close");
client.println();
client.stop();


DF Robot W5200 Ethernet Shield for an Arduino Uno not working? I've been working on using an ethernet shield for my Arduino Uno for a couple weeks now. I've been going through the problems one by one and now realise that there seems to be nothing transmitting. Running code similar to DHCPAddressPrinter results in nothing, and any web server I set up does not work at all. Can anyone please help? Running the code below results in an output of "Baud rate set!" and nothing else. One thing to note is that the MAC address I am using is from going into the command prompt and using the MAC address listed from ipconfig /all, as there is no sticker on the ethernet shield itself.

    /*
    DHCP-based IP printer

     This sketch uses the DHCP extensions to the Ethernet library
     to get an IP address via DHCP and print the address obtained.
     using an Arduino Wiznet Ethernet shield.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13

     created 12 April 2011
     modified 9 Apr 2012
     by Tom Igoe

     */

    #include <SPI.h>
    #include <EthernetV2_0.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on         the shield
    byte mac[] = {
      /*MAC Address here*/ };

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
     // Open serial communications and wait for port to open:
      Serial.begin(9600);
      Serial.println("Baud rate set!");

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for(;;)
        Serial.println("FAIL");
          ;
      }
      // print your local IP address:
      Serial.print("My IP address: ");
      for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
      }
      Serial.println();
      Serial.println("Loop");
    }

    void loop() {

    }

Don't use the MAC address of your computer read from ipconfig output. It creates a conflict on LAN. Use the MAC address from examples.

To troubleshoot Ethernet shield, use the Ethernet library newest version 2.00. It supports W5100, W5200 and W5500 and has better diagnostic in examples.

And to troubleshoot, always connect the LAN cable to router or switch, not to computer, because direct connection to computer requires manual setup of addresses (no DHCP).


Declaring and using array of structures in Arduino Printing structure variables, I get default values. What is wrong with my code?

struct SCENARIO
{
  int Lamp_Pin = -1;
  int PB_Pin = -1;
} ;

SCENARIO  _red;
SCENARIO  _yellow;
SCENARIO  _white;
SCENARIO  _stop;
SCENARIO btns[4] = { _red,  _yellow, _white, _stop};

void setup()
{
  _stop.Lamp_Pin = 8;
  _stop.PB_Pin = 4;

 ///// initializing other 3 objects i.e. red & white & yellow
 ////
for (int i = 0; i < 4; i++)
  {
    Serial.print(i);Serial.print(":");
    Serial.print(btns[i].Lamp_Pin);Serial.print(":");
    Serial.println( btns[i].PB_Pin );
    //pinMode(  btns[i].Lamp_Pin, OUTPUT);
    //pinMode(  btns[i].PB_Pin, INPUT);
  }
}

The image below shows what I get. It seems I have not initialized the variables!

The problem is that a struct is handled as a value type, not as a reference type.

This means that a copy of _stop is made and put in btns (btns[3] actually).

So what you need to do is putting pointers into the btns array:

SCENARIO* btns[4] = { &_red, &_yellow, &_white, &_stop};

The symbol * denotes a pointer, and & means the address of a variable (so it points to the variable and is not a copy).

Now when you change _stop, also btns[3] which points to _stop will show the correct initialized value.

For printing you should use:

Serial.println( (*btns[i]).LampPin);Serial.print(":");
Serial.println( (*btns[i]).PB_Pin );

Because *btns[i] is a pointer, but because this is a very often used feature, a special notation can be used:

Serial.print(btns[i]->Lamp_Pin);Serial.print(":");
Serial.println( btns[i]->PB_Pin);


Lego Technic Servo Motor - 9V PWM I want to control Lego Technic Servo Motor 88004.

The way it works is - Lego has a 4 cable connector. Two of them supply power (+9V & GND) and the other are optionally +9V and they are called C1 and C2.

Servo turns right or left max 90 deg when you supply PWM to either C1 ("left") or C2 ("right"). (or the other way round, but it doesn't really matter)

That basically means that what I need is a 9V PWM and be able to supply it to either C1 or C2. What is more the frequency has to be 1150 Hz.

Now the question is how do I achieve this goal?

I'm already using the L298N motor controller and happen to have one engine slot free.

1) If I can supply PWM from Arduino to "LNA" input in L298N - will it also cause the output to be PWM?
Because L298N has a transistor I have a feeling that the output is also going to be PWM unless there's something else there i.e. capacitor

Even if it's not does that matter at all - meaning is it going to still work?

2) How do I produce PWM with 1150 Hz from Arduino? My Arduino is 16MHz so I suppose that it should be possible to switch output with order of magnitude smaller frequency.

If what I'm trying to do makes no sense please try to point me to the right direction.

Yes, the output will be a pwm. You can see it from the schematics.
you have few options, with different precision and complexity:

Configure one of the PWM HW blocks
Do it by sw in a loop
Use a timer to trigger a sw function - but it might be simpler to just configure the PWM HW block.
Use some existing library that will implement one of the methods I listed

I would recommend Option 1: it's not so difficult, you will learn something of the AVR internals and it will be the solution with the least overhead. You can have a look at this tutorial. There are also many others floating around.


Arduino IDE on Fedora I'm using Fedora_21_MATE.img on a Raspberry Pi. Installing the Arduino IDE 1.0.6 using these commands, taken from Arduino On Pi. Those instructions are for Raspbian, I assume, so changing for Fedora, apt-get to yum:

sudo yum install arduino

One waits and arduino installs. One can then run the Arduino IDE from the Fedora GUI menu, and it loads - after moaning about the user has to be a member of the dialout and lock groups. This is easily resolved by adding the user to the required groups, using the control panel.

However, trying to compile anything, i.e. blink, in the IDE, gives me the following error:

avr-g++: error trying to exec cc1plus: execvp: No such file or directory

In verbose mode, little additional information is offered.

Arduino: 1.0.6 (Linux), Board: "Arduino Uno"
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build6314348775898760987.tmp/Blink.cpp -o /tmp/build6314348775898760987.tmp/Blink.cpp.o
avr-g++: error trying to exec 'cc1plus': execvp: No such file or directory

The file in question, cc1plus, is actually present in the filesystem:

[piebody@berrybody ~]$ locate cc1plus
/usr/libexec/gcc/armv7hl-redhat-linux-gnueabi/4.9.2/cc1plus
/usr/libexec/gcc/avr/4.9.2/cc1plus
[piebody@berrybody ~]$

Does anyone know why it doesn't run "out of the box"? Do I need to modify any environment variables, and if so, which ones and with what exactly? I assume my PATH environment variable needs fixing, but is there any environment variable specific to avr-g++ that needs changing?

I appreciate that this is probably a simple UNIX paths issue, and that the question may be more suited to SE: Unix & Linux.

There seem to be two issues:

Getting the IDE to fully function when launched from the command
line, and;
Getting the IDE to fully function (i.e. compile) when launched from
the Fedora GUI menu.

I have found a solution if I run the Arduino IDE from the command line, by adding the path to  one of the cc1plus binaries to the PATH environment variable:

[piebody@berrybody ~]$ PATH=${PATH}:/usr/libexec/gcc/avr/4.9.2
[piebody@berrybody ~]$ export PATH
[piebody@berrybody ~]$ arduino&

However, if I launch the Arduino IDE from the Fedora application menu, and then try to compile a sketch, it still can't locate cc1plus. Maybe the PATH needs to be added in my .profile, or some other mechanism, to get an application launched from the Fedora menu to see the path?1

Yet, even with the command line launch, it still does not finish compiling.  I now get the following error when the IDE attempts to compile:

In file included from Blink.ino:18:0:
/usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:23:20: fatal error: stdlib.h: No such file or directory
 #include <stdlib.h>
                    ^
compilation terminated.

In verbose mode

Arduino: 1.0.6 (Linux), Board: "Arduino Uno"
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build1210300884764677972.tmp/Blink.cpp -o /tmp/build1210300884764677972.tmp/Blink.cpp.o
In file included from Blink.ino:18:0:
/usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:23:20: fatal error: stdlib.h: No such file or directory
 #include <stdlib.h>
                    ^
compilation terminated.

I assume that this is another PATH issue. One that relates to the path to the Arduino libraries, or libc libraries.

After reading can't locate avr libraries2, I can't see why avr-g++ is not picking up the avr directory in the /usr directory.

The actual path to stdlib.h is /usr/avr/include/stdlib.h

The output of avr-gcc (and avr-g++) shows --prefix=/usr

The Arduino IDE preference file (~/.arduino/preference.txt) shows the line

last.ide.1.0.6.hardwarepath=/usr/share/arduino/hardware

Linking the includes

If I manually link some header files to where the compiler actually is looking, then it works (until avr-gcc needs a header that I have not linked to):

cd /usr/share/arduino/hardware/arduino/cores/arduino
sudo ln -s /usr/avr/include/stdlib.h stdlib.h
sudo ln -s /usr/avr/include/string.h string.h
sudo ln -s /usr/avr/include/math.h math.h

but I can not do this for every header file, it is ridiculous. There must be a way of linking to /usr/avr from /usr/share/arduino/hardware/arduino/cores/arduino. I have tried linking the parent directories /usr/avr and /usr/avr/include, at various points along the directory hierarchy of /usr/share/arduino/hardware/arduino/cores/arduino, but none of those seem to work.

Copying the include directory

After reading default include file path?, and running avr-cpp -v I saw that the default #include search path was

#include <...> search starts here:
 /bin/../lib/gcc/avr/4.9.2/include
 /bin/../lib/gcc/avr/4.9.2/include-fixed
End of search list.

From this, I could see that avr-cpp was searching in /lib/gcc/avr/4.9.2/include. I examined, and compared, the contents of /lib/gcc/avr/4.9.2/include with /usr/avr/include and they held similar (the same) files, except /lib/gcc/avr/4.9.2/include was a subset, that is to say that it was missing the required files.

I ended up copying the /usr/avr/include directory, which contains the required header files (stdlid.h etc., to which I had linked previously), and replacing the original include directory, in the directory where avr-gcc seemed to be looking, which was in its own directory location /lib/gcc/avr/4.9.2/.

cd /lib/gcc/avr/4.9.2/
mv include include.old
cp -r /usr/avr/include .

Then the Arduino compiler seemed to work, until it then gave an assembler error:

Assembler messages
Error: unrecognized option -mmcu=avr5

This is an issue with avr-as.

I will update as I resolve these issues.

1 I eventually resolved this by creating a script in /usr/bin (where the arduino binary was located) called arduino.launch which contains the PATH settings and a call to arduino:

#!/bin/sh
PATH=${PATH}:/usr/libexec/gcc/avr/4.9.2
export PATH
arduino

setting it to be executable with chmod +x arduino.launch. Then I edited the properties of the Fedora Arduino launch icon, by right-clicking on the icon and selecting Properties, and changed the Command entry from arduino to arduino.launch.

However, there must be a better way of doing this, as this seems to be a bit of a hack.

2 Other posts 1, 2 and 3) that I have read, apart from providing useful paths to investigate, merely suggest reinstalling. However, as bone headed as I may seem, there must be a way of linking up what is already on the file system (everything is there - just in the "wrong" place), such that compiles work as they should.


ESP32 not seen by a network analyzer application in server mode I have used the scan wifi and blink examples provided by Espressif,
they are both working on the ESP32 using arduino ide.

However, I can not see my ESP( the SSID and signal strength) in the list of detected wifi when searching for it using a network analyzer app  ( Net analyzer on android)

This was solved when I used the ESP as Access point.
In Client mode the ESP is using the WIFI capability. But why it can not be seen by others?

why is the ESP32 Lolin getting hot only when it is in AP mode?

Thanks in advance

In Client mode the ESP is using the WIFI capability. But why it can
  not be seen by others?

The app is looking for access points. (if it is looking for SSID) And if you do not have the ESP set as an access point it will not be seen.

  why is the ESP32 Lolin getting hot only when it is in AP mode?

Because the radio is on all the time. It has to be available for a connection. When it is not an access point, the ESP goes into a sleep mode when it does not have any need to communicate.


How to implement brown out detector arduino ESP32? We are using ESP32 with arduino sdk for developing our application. In our application we need to implement BOD to detect with specific voltage level.
Basically we want to set specific voltage level and when device goes to power off it will detect and trigger interrupt. How I can set interrupt for brown out detect?
we have only this code:
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"

void setup() {
  Serial.begin(115200);
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 1); //enable brownout detector
}

void loop() {
  Serial.println("Start BOD");
  delay(1000);
}

The ESP32's on-board BOD is mainly intended to inhibit operations that might cause corruption if they happened with too low a voltage.  There is a very unpredictable amount of time for the code in the ESP32 to do anything but effectively halt.
If that's what you want, then you have enabled it in your code above.
If you want to detect a power outage, for example, and log something, then you need two things:

A reliable detector that the power has failed.
A battery or capacitor-based circuit that will continue the ESP32's power for long enough for you to do what you need to do.

So when "1" happens you set a GPIO pin on the ESP32 which triggers your interrupt and you do what you need to do while the power remains stable.


Not showing output when using pins other than 10 and 11 with SoftwareSerial library on Arduino Mega I am  trying to run below code on Arduino Mega using GPS module(skg13 bl). It is working fine with pins 10, 11 as rx, tx in the SoftwareSerial but it is not showing output when other pins such as 4, 5 are used.

I further have to send this data through RF module using virtual wire library.

Code is as follows:

#include <SoftwareSerial.h>
#include <TinyGPS++.h>
TinyGPSPlus gps;

SoftwareSerial mySerial(10, 11);

void setup() {
  mySerial.begin(9600);
  Serial.begin(9600);
  Serial.println("GPS start");
}

void loop() {
  while (mySerial.available()) {
    gps.encode(mySerial.read());
  }

  if (gps.location.isUpdated()) {
    double a = gps.location.lat();
    Serial.println(a);
    Serial.println(gps.location.lat(), 6);
    double b = gps.location.lng();
    Serial.println(gps.location.lng(), 6);
  }
}

Thanks in advance!!

From https://www.arduino.cc/en/Reference/softwareSerial:

  Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

So you will need to use one of the pins from that list for RX, pin 4 or 5 will not work.


Arduino Uno with HC-SR04 Power saving My Arduino Uno is powered by 9v battery to run 2 ultrasonic sensors (HC-SR04) and a buzzer.
I intend let the circuit run for at least a week.
Is there a solution to reduce power consumption / increase battery life?
I am open to hardware and software solutions.
Thanks!

You could do a checking routine. For example, if you are detecting motion you can connect the vcc pin of the HC-04 to a digital pin and turn it on and check for changes once every 10 seconds.


Arduino IDE fails without sudo I use Arduino IDE 1.6.6 on Ubuntu 15.10.

Starting the Arduino IDE without using sudo fails for both:

uploading the code to the Arduino Uno
starting the serial monitor

The group I need to add my user to is called dialout:

myuser@mycomputer:~$ ls -l /dev/ttyACM*
crw-rw---- 1 root dialout 166, 0 Dez 12 17:57 /dev/ttyACM0

So I added myuser to dialout:

sudo usermod -a -G dialout myuser

Somewhere I read that I have to add myuser to tty as well, so I did it:

sudo usermod -a -G tty myuser

Though I still fail with the above mentioned when trying to use the IDE with myuser.

What do I have to do to get the IDE working with myuser?

There should be a command like 'id' or something similar that will show the groups you are a member of. Run that to check that the new groups have taken effect – you may need to log out and then log back in.

The other thing to check is the group owner of the device itself (in /dev). that will also need to match the group you assigned to yourself. Also make sure that the device permissions allow group access.


Enable free fall detection using Arduino I'm trying to get an arduino board to detect simple free fall condtions. Currently, I have a 9DOF sensor (https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide) and am able to get the raw data from the sensor.

However I am unsure what to do from here onwards. From what I manage to gather, there is an alternative sensor ADXL345 accelerometer that has an inbuilt free fall component. I have tried modfying the code in such a way that it will work with the sensor I am using but to no avail.

The free fall detection does not need to be extremely accurate/precise considering there are many fall/jerk patterns. It is just for a proof of concept for a project of mine. With that in mind, any suggestions on how to proceed will be greatly appreciated (or if I should just get the ADXL345 accelerometer).

Thank you.

Sitting an accelerometer flatly on a bench will produce a value of 1G in one of the 3 axes.

Free fall of an accelerometer (assuming you haven't reached terminal velocity) should read near zero on all 3 axes.

I am not aware of a mode you can set for this, but if you check the values of the 3 axes and all are close to zero, you are probably in a free fall condition.


Trying to do hello world app for Nokia 5110 LCD with arduino yun and johnny five I have a Nokia 5110 LCD which is using this display PCD8544, I am using a arduino yun and johnny five I have hooked up the following pins. So far with my node app all that happens is the lcd lights up. I am not sure if maybe the lcd is not supported with johnny five, if I have a pin wrong. I followed this site for the pin setup https://lastminuteengineers.com/nokia-5110-lcd-arduino-tutorial/ Any help would be greatly appreciated. This is my first attempt with Johnny five and second attempt at hooking anything up to a bread board. Hope we can get this working. Thanks

Here is my code

const five = require('johnny-five');
const board = new five.Board();

board.on("ready", function() {

    lcd = new five.LCD({
      controller: "PCF8574"
    });

    lcd.print("Hello");
  });

Here is my configuration

blue         =  pin 7          sclk     (serial clock(CLK)) 10 om
white        =  pin 6          DN(MOSI) (Serial data in) 10om
grey         =  pin 5          D/C      (Mode select) 10om
orange       =  pin 4          RST      (Reset) 10om
yellow/red   =  pin 3          SCE      (Chip select) 10om
yellow-short =  power strip +  LED      (backlight supply) 1kom
green/black  =  gnd / strip -
blue/power   =  3.4v power + 330om

Here is are some images of the setup

Update so my configuration looks more like this now

blue         =  pin 7          sclk     (serial clock(CLK)) 10k
white        =  pin 6          DN(MOSI) (Serial data in) 10k
grey         =  pin 5          D/C      (Mode select) 10k
orange       =  pin 4          RST      (Reset) 10k
yellow/red   =  pin 3          SCE      (Chip select) direct
yellow-short =  power strip +  LED      (backlight supply) 330
green/black  =  gnd / strip -
blue/power   =  3.4v power powerstrip direct

Arduino Yun is a ATMega32U4-based board, like other ATMega32U4-based Arduino boards, such as Arduino Leonardo, Micro, the SPI is only available on the ICSP header:

MOSI - Yun has it on ICSP Pin 4
MISO - Yun has it on ICSP Pin 1
SCK - Yun has it on ICSP pin 3
SS - Yun has no dedicated pin, use any digital data pin

You can find out the ICSP header pin assignment at Arduino SPI reference page. So here is the connection between Arduino Yun and LCD5110

Yun               LCD 5110
ICSP pin3         CLK(SCK)
ICSP pin 4        DN(MOSI)
any GPIO pin      D/C (see note 1)
RST               RST
any GPIO pin      SCE(SS) (see note 1)
any GPIO pin      Backlight (via a 330 ohm resistor) (see note 2)
GND               GND
3v3               VCC

  Note 1: Although you could use any GPIO for D/C and SCE, you should consult the library that you are using to see what pin the library used for the data/command line and SS line.

  Note 2: Connecting to a GPIO pin allows you to turn on and off the LED backlight, you could ignore the connection if you don't want the backlight, or you could connect it directly to 3v3 via a resistor if you want backlight on permanently

If you still have problem in using the LCD5110, please update your question with complete code and the library that you are using.


What is this potentiometer for? I am working on an anemometer project using Arduino. I don't know barely anything from Arduino and I am following this tutorial.
I have some doubts on the making part. This is what I have to make:
and this is the code:
//anemómetro con LCD
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

float veloc1 = 0; // entrada A0
int tiempo = 0;
int cnt = 0;
float v1 = 0;
float v2 = 0;

void setup() {
  lcd.begin(16, 2); // Fijamos el numero de caracteres y filas
  lcd.begin(16, 2); // Fijamos el numero de caracteres y filas
  lcd.print("Anemometro EC"); // Aqui va el mensaje
  analogReference(INTERNAL);// pone como referencia interna 1.1V
}

void loop() {
  v1 = (analogRead(0)); // lectura de sensor a0
  veloc1 = (v1 * 0.190); // 0,190 corresponde a la pendiente de la curva aca deben poner el numero que calcularon
  lcd.setCursor(0, 1); // Ponte en la line 1, posicion 0
  lcd.print(veloc1); //muestra la velocidad del viento en el LCD
  lcd.setCursor(4, 1); // ponte en linea 1, posicion 5
  lcd.print("Km / h");
  lcd.setCursor(9, 1);
  lcd.print("Max");
  if (veloc1 > v2)v2 = veloc1, lcd.print (v2, 1); // muestra la velocidad maxima que alcanzo
  delay(1000);
}

What is the potentiometer doing here? Why is it necessary?
My lcd screen doesn't show anything. Does anyone knows why??

Thanks in advance.

What is the potentiometer doing here? Why is it necessary?

It's there to control the "offset voltage" of the LCD, which is what controls the contrast of the display.

My lcd screen doesn't show anything. Does anyone knows why??

Maybe you wired it wrong. Maybe you didn't put the potentiometer in the circuit because you didn't understand what it is for. Maybe you just need to adjust the contrast by turning said potentiometer. It's hard for us to tell. By showing us what you intended to build and then telling us that what you actually built doesn't work, there is nothing we can tell you. There must be some difference between what you intended to build and what you did build, but we can't see what you built, so we can't have any clue.


My Arduino Fingerprint Sensor FPM10A is not working with an Arduino Nano with Atmega168 processor I recently bought this Arduino Fingerprint Sensor FPM10A from Aliexpress. So, when I connected it with my Arduino Nano and uploaded the 'enroll' example and opened the serial monitor. The fingerprint print sensor got detected but when I enter #1 to enroll the fingerprint no output is given on the serial monitor. I think my Arduino Nano just freezes.But other examples such as 'Empty database, it works with no problems. Is this caused by the less powerful Atmega168 microprocessor? If I get a Arduino Uno or an Arduino Nano with an Atmega328P microprocessor will this problem be solved? And I do not think the fingerprint module is defective as other examples worked like a charm.
Please see the attached photo above.

Did you buy the arduino board Nano Atmega168 on Aliexpress? Sometimes the cheapest arduino compatible boards are okay, but sometimes they are stripped of decoupling capacitors or the polyfuse is missing (on a uno board). Sometimes they put a Atmega168 on the board, it is a few cents cheaper.

If you buy the cheapest nano compatible board, look at the photo if the quality is reasonable. The newer arduino boards have a ARM Cortex processors. The Atmega328p is still okay for small projects. I suggest to use the Atmega328p as the minimum.
A Arduino nano Atmega328p clone at Aliexpress costs about 2 dollars, so there is no reason to buy an Atmega168.

When the compiler tells you that "Low memory available, stability problems may occur" for the ram, then you can almost be sure that it will not work.

I try to keep about 300 bytes ram available for local variables, stack and the heap. It depends how much memory the libraries require. I also don't use the String objects for the Arduino uno or nano.
For a beginner, you can try to keep at least 500 bytes ram available.


Does blinking an LED with no resistor for a few seconds harm my Arduino? I am new to Arduino and I just made my first LED blink. I connected the LED to ground and digital pin 13 without resistance (for only a few seconds). Does this harm my Arduino?

Hilmi

If you try it again with the proper resistor in place, and the pin still works, then no, you probably haven't damaged it. It may have stressed the pin driver some but if it passes the above test, I think you're still good to go.


Arduino does not work When I try to upload a sketch to my Arduino Uno R3 then sometimes I get the following issue:

At the beginning the RX LED flashes three times and then I get errors:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd1

Sometimes I get this:

    avrdude: ser_open(): can't open device "\\.\COM3": Odmowa dostępu.

And sometimes Windows does not see the Arduino.

At this site Have I bricked my Arduino Uno? Problems with uploading to board I read that to check the programmer I must to connect RX with TX and GND with RESET pins and then plug Arduino to my computer, open Serial Monitor and write anything and if you receive the same characters from the Arduino, then the programmer and USB cable are OK. It worked for me.

And I have got one more info. When I plug Arduino with USB to my laptop the L led lights. When I press Reset on Arduino nothing happens, it still lights.

I recently bought a new USB cable, and it worked one day and then I could not upload sketches again. I uninstalled and installed drivers, but nothing changed.

This is a short video with my Arduino https://drive.google.com/file/d/0ByeWvrEgy2gRbWdHQ3d5RWU3Mmc/view?usp=sharing

I will buy USBasp programator is it a good idea?

It's normal that the L-LED is steady on after the USB connection is established. However, after pressing and releasing Reset it should flicker for a second, then go back to on again.

Check https://www.arduino.cc/en/Guide/Troubleshooting#toc1 for reasons why you can't upload.

On http://www.arduino.org/products/boards/4-arduino-boards/arduino-uno I've found:

  The Arduino Uno has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.

I haven't found out so far, how to read the current values of the fuses.


Displaying characters as bitmaps I have resorted to creating bitmaps for each number and a few letters for a 128x64 Oled module. This was to save memory and get around limitations of libraries such as the u8glib. If I had linux I could use the tools they provided to fix some of these but that's out of the question for now. I wanted to know if there's a simple way of mapping each character to it's bitmap so a function similar to XXX.print(); be used, in order to parse the characters and display the corresponding bitmaps automatically. That would make my life so much easier! thanks!

I would split it down into functions.

First write a function which takes a character and a pair of coordinates, then draws the bitmap corresponding to that character at the given coordinates on the screen.

Then you want a function that is the "next level up". You just pass it a single character, and it remembers the current coordinates and uses those with the character to call the first function. It's then the job of this function to move the coordinates to the next character location ready for the next time it's called.

Finally you want an outer layer (or a few outer layer) functions that take different data types (const char * for example) and send each character in turn to the second function above.

If you were to make a class to wrap it all in you could inherit the Print class. That means you just need to provide the size_t write(char) function which is equivalent to the second function above (of course you still need the first function). The wrappers for different data types are then all provided for you.


Which relay module to buy and what is the difference between 1 channel and 2 channel relay boards I wanted to d a simple circuit using Arduino to control the lights in my house. But i do not know which relay module to use my house runs on standard 220v ac.
Can anyone tell me weather this relay board will be enough
https://www.roboelements.com/wp-content/uploads/2018/10/1-Channel-5V-Relay-Module-for-Arduino-with-Optocoupler.jpg
Or should I buy a 2 channel one?
And another thing what is the difference between 1 channel and 2 channel relay board.
I'm a complete beginner, so please help me out.

Yes, you can use those. You have to watch a few things:

Input voltage: 5V, perfect for Arduino
Output voltage: 220 V, perfect for 220V AC
Output amperage: 10A, what you control should use max 10 A, and I would use max 5A, and also consider switching on current into account. However, 10A is a lot of current.

The difference between 1 and 2 channels relay boards, is just that there are either 1 or 2 of them, meaning you can control 1 or 2 motors independently from each other.


How to interface to LPG consumption meter I have sourced an LPG consumption meter from China with pulse output. I am looking to hook the output up to an arduino to get the consumption metrics. Unfortunately there is not too much documentation available on the unit that I can find. The suppliers inform me that:

Black wire(signal 1)
Black wire(signal 2)
Red wire(earth wire)

So that's a start, I know the unit pulses a signal for every cubic meter of gas consumed.
What I'm wanting to know is:

What are the input [likely] voltages for the unit (or how could I establish this)?
How do I wire the unit to an arduino?
I can cook up a sketch to do the reading but what is the signal I am looking for?

The mechanical meter itself has a metallic strip on the 0 digit of the wheel (how it achieves the pulsing itself no doubt) so another approach would be something like this http://phk.freebsd.dk/Gasdims/ which is a more accurate option. For this option any suggestions on what photoreflectors are available for the Arduino which could do the job.

Start with earthing the red (!?) wire to the ground of the arduino.
Apply 5 volts via a 10k resistor to one of the black wires and also connect the black wire to the arduino as well.
Basically :

5V ----(10K resistor)---+---Black wire----( Gas Meter)-----ground
                        |
                        |
                        +--- arduino digital input

You should either get a high or a low signal. Try the other black wire, it might be inverted (as in high and then pulse low, vs low and then pulse high).

Failing that, pop the top off that cover and have a poke around. Might give you a clue as to what's what.


unresolved overloaded function type for Wire.onReceive I am attempting to make an I2C slave out of my Arduino and I can't get past the Wire.onReceive function. Here is my code. The documentation says to just add a function that has the style of void myHandler(int bytes) but I can't figure out why my readPI function does not meet these requirements.

    #include "piCom.h"
    #include "WireAddresses.h"
    #include <Wire.h>

    pi::pi(){
       Wire.begin(NB_INFO); // is 0x04
       Wire.onReceive( readPI );
       //Wire.onRequest(sendPI);
    }

    void pi::readPI(int byteCount){
       while( Wire.available() ){

             ref_IMU = Wire.read();

       }//end while

    }//end readPI

    void pi::sendPI(){

       Wire.write(1);
       //use to send pressure info to pi

    }//end sendPI

    //double pi::getref_IMU(){return ref_IMU;}

then here is the error

piCom.cpp: In constructor 'pi::pi()':
piCom.cpp:7: error: no matching function for call to'TwoWire::onReceive(<unresolved overloaded function type>)'
 Wire.onReceive( readPI );
                        ^

no matching function for call to 'TwoWire::onReceive(<unresolved overloaded function type>)'

Any help is greatly appreciated.

void pi::sendPI(){

That is a class function (method) which has an implicit this pointer. You can't use it as a static ISR.

In general, classes cannot implement ISRs for this reason. There are a few workarounds, one being to make it a static class function. However then it will affect the entire class, not just one instance.


declaration of 'varDay' as array of references error I am trying to write a function to store the date and time data from an RTC module. I have used char arrays to implement the function. I get "declaration of 'varDay' as array of references" error upon compilation.
I am still learning about char arrays and manipulating them so may be I am making a very obvious mistake. Could you please explain what I am doing wrong?
#include <RTClib.h>

RTC_DS3231 rtc;

void setup() {
  Serial.begin(115200);
#ifndef ESP8266
  while (!Serial); // wait for serial port to connect. Needed for native USB
#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

}

void loop() {
  unsigned long newTime = millis();
  static unsigned long oldTime = 0;

  char varYear [] = "1234";
  char varMonth [] = "00";
  char varDay [] = "00";
  char varHour [] = "00";
  char varMinute [] = "00";
  char varSecond [] = "00";
  unsigned int varEpoch;
  char varDate [] = "123456789";
  char varTime [] = "12345678";
  char dash [] = "-";
  char colon [] = ":";

  if (newTime - oldTime >= 60000) {
    oldTime = newTime;

    getDate(varDay, varMonth, varYear, varDate, dash, colon);
  }

}
void getDate (char &varDay[3], char &varMonth[3], char &varYear[5], char &varDate[11], char &dash[2], char &colon[2]) {

  DateTime now = rtc.now();
  strcpy (varDay, now.day());
  strcpy (varMonth, now.month());
  strcpy (varYear, now.year());

  strcat (varDate, varDay) ;
  strcat (varDate, dash);
  strcat (varDate, varMonth);
  strcat (varDate, dash);
  strcat (varDate, varYear)

  Serial.println(varDate);
}

char &varDay[3] is an array of 3 references to type char, not a reference to type char of size 3.
Instead just pass a pointer:
void getDate (char *varDay, char *varMonth, char *varYear, char *varDate, char *dash[2], char *colon[2]) {

Also:
strcpy (varDay, now.day());
strcpy (varMonth, now.month());
strcpy (varYear, now.year());

That won't work. You can't copy a number into a string. now.day() etc need converting to a string first.
It would be better to format your string with snprintf:
snprintf(varDate, 11, "%02d-%02d-%04d", now.day(), now.month(), now.year());


How does this code work? I've found this code below, but I can't figure out how it works. Can someone explain to me the flow of the program?

#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 10, 7, 5, 4);
int mem=0;
void setup() {
    pinMode (12,OUTPUT);
    pinMode(13,OUTPUT);
    // initialize the LED pin as an output:

    // initialize serial communications:
    Serial.begin(9600);
    lcd.begin(16, 2);
}

void loop() {

    lcd.setCursor(12,1);
    int se25 = analogRead(A4);
    int se50 = analogRead(A3);
    int se75 = analogRead(A5);
    int se100 = analogRead(A2);
    if(se100>=1000){lcd.print("100%   ");mem=100; }
    else if(se75>=1000){lcd.print("75%   ");mem=75; }
    else if(se50>=1000){lcd.print("50%   ");mem=50; }
    else if(se25>=1000){lcd.print("25%  ");mem=25; }
    else{lcd.print("emty");mem=0;}
    if(se100<1000&&se75<1000&&se50<1000&&se25<1000){
        digitalWrite(13,LOW);
        lcd.setCursor(12,1);
        lcd.print("emty");
    }

    if(digitalRead(6)==HIGH){digitalWrite(13,LOW);}

    if(digitalRead(6)==LOW&&mem>0)
    {// read the value of the potentiometer:
        int tempw = 0;
        //digitalWrite(12,LOW);
        int tempa = analogRead(A1);
        delay(20);
        int tempb = analogRead(A1);
        delay(20);
        int tempc = analogRead(A1);
        delay(20);
        int tempd = analogRead(A1);
        delay(20);
        int tempe = analogRead(A1);
        delay(20);
        int tempf = analogRead(A1);
        delay(20);

        int avg = ((tempa + tempb + tempc + tempd + tempe + tempf ) / 6);

        int temp = avg;
        // map it to the range of the analog out:
        temp = map(temp, 0, 1023, 0, 4900);
        float tempx = temp * (0.1);
        // change the analog out value:
        int tempy=analogRead(A0);
        tempy = map(tempy, 0, 1023, 0, 150);
        // print the results to the serial monitor:
        lcd.setCursor(0,0);
        lcd.print("act T=" );
        lcd.print(tempx);
        lcd.print("'C  " );
        lcd.setCursor(0,1);
        lcd.print("set T=");

        lcd.print(tempy);
        // Serial.println("'C ");
        lcd.print("'C  ");

        if(tempy<=tempx){digitalWrite(13,LOW);}
        if(tempy>tempx){digitalWrite(13,HIGH);}

        delay(200);
    }

}

I'm assuming you already have some understanding of programming, so I won't literally explain everything line-by-line (that would probably be beyond the scope of this site, and would result in a very long answer). I'll try to explain the important points though. If you need to lookup more information about specific commands, I recommend checking out the Arduino reference.

At a very broad level, the program is taking some readings, and reporting data to a screen (LCD). I would guess that the data is the fluid level in a tank, as well as some kind of temperature reading. It's impossible to be sure about that though, as I don't know what's actually connected to the inputs.

This line creates an object for talking to the LCD screen. The numbers specify which pins it's connected to:

LiquidCrystal lcd(2, 3, 10, 7, 5, 4);

The setup() function gets run once when the device starts up, and is typically used for initialisation tasks. In this case, the lines within setup() initialise two pins as outputs (#12 and #13), initialise serial communication (which isn't actually being used), and initialise the LCD object/screen:

pinMode (12,OUTPUT);
pinMode(13,OUTPUT);
...
Serial.begin(9600);
lcd.begin(16, 2);

The rest of the program is in the loop() function, which runs repeatedly as long as the device is on.

The following lines take 4 analog-to-digital readings (from different inputs), and output the approximate result:

int se25 = analogRead(A4);
int se50 = analogRead(A3);
int se75 = analogRead(A5);
int se100 = analogRead(A2);
if(se100>=1000){lcd.print("100%   ");mem=100; }
else if(se75>=1000){lcd.print("75%   ");mem=75; }
else if(se50>=1000){lcd.print("50%   ");mem=50; }
else if(se25>=1000){lcd.print("25%  ");mem=25; }
else{lcd.print("emty");mem=0;}
if(se100<1000&&se75<1000&&se50<1000&&se25<1000){
    digitalWrite(13,LOW);
    lcd.setCursor(12,1);
    lcd.print("emty");
}

My guess is that each of the analog readings comes from a different fluid sensor in a tank. If the top sensor shows a strong reading, the tank is considered full. Otherwise, it checks the next sensor down, and so on. If none of them shows a strong reading, the tank is considered empty. Interestingly, the condition for an empty tank is actually checked twice, which is presumably a mistake.

(Once again, bear in mind that I'm just guessing that the readings are from fluid sensors in a tank. I don't know for sure.)

The remainder of the code only runs if a particular input (#6) is low, and if the tank is not empty. Input #6 could be from some kind of override switch, but again that's just speculation.

The following block takes 6 analog readings, all from the same input. There's a short delay (20 millisecond) between each reading. The results are then averaged. This is a common approach when you want to try to eliminate noise spikes in an analog signal.

int tempa = analogRead(A1);
delay(20);
int tempb = analogRead(A1);
delay(20);
int tempc = analogRead(A1);
delay(20);
int tempd = analogRead(A1);
delay(20);
int tempe = analogRead(A1);
delay(20);
int tempf = analogRead(A1);
delay(20);

int avg = ((tempa + tempb + tempc + tempd + tempe + tempf ) / 6);

The next block re-maps that reading onto a different range (presumably related to the expected temperature range). It then takes another analog reading from a different input, and remaps that to a different range:

int temp = avg;

temp = map(temp, 0, 1023, 0, 4900);
float tempx = temp * (0.1);

int tempy=analogRead(A0);
tempy = map(tempy, 0, 1023, 0, 150);

The following block outputs the two re-mapped readings. It looks like both of them are treated as temperatures. One is presumably from a temperature sensor, and the other is presumably from a potentiometer used to calibrated the system:

lcd.setCursor(0,0);
lcd.print("act T=" );
lcd.print(tempx);
lcd.print("'C  " );
lcd.setCursor(0,1);
lcd.print("set T=");

lcd.print(tempy);

lcd.print("'C  ");

These lines compare the two readings from above, and set output pin 13 high or low depending on which reading is higher. I'd guess it could be connected to a warning light or similar.

if(tempy<=tempx){digitalWrite(13,LOW);}
if(tempy>tempx){digitalWrite(13,HIGH);}

Lastly, this delay stops the loop from running too fast. Interestingly though, the code only reaches this point under certain circumstances. In other circumstances, there's no limit on loop execution speed:

delay(200);


How to Work Two Linear Actuator Synchronously by Using Arduino and VNH5019 Motor Driver? I am newbie and I want to build a project that contains two linear actuator that move synchronously. Two of them will lift up and down at same time. I use arduino mega and VNH5019 motor driver. I have thompson electrac ELD linear actuator. I have never tried to synchronize two linear actuator. Linear actuator have encoder output ( it is hall effect encoder -( not absolute. So it cannot keep last position in case of power cut )). Encoder type is hall effect type. Encoder output voltage levels low (logical zero), typical / max is 0.1/0.25 Vdc. Also it has output fully extented/retracted signal. I tested it with H-Bridge motor driver made of 4 SSR relays and push button switches to retract and extract. There is a synchronization problem.The system will stop when actuators extracted 500 mm ( actuators have 900 mm stroke length) How should I solve that synchronozation problem could you help me ? What should I do?

It sounds like you need to watch both encoder outputs and don't let one get ahead of the other. Naturally, they won't sync exactly (i.e., pulse simultaneously) but you can set a limit on how many counts to let them differ by, before pausing the faster actuator while the slower one catches up.

If you need to save positions across a power failure, you'll need to 1) provide enough backup power to keep the system alive past the supply failure to give you time to stop both actuators and store both of their positions in EEPROM; and 2) provide a signal to the Arduino that the supplied power (not the backup) is going down, so it can begin its orderly shutdown.


analogWrite(PIN, 1023)  digitalWrite(PIN, HIGH) This question is very similar to this one.
I'm using an ESP8266 for which the maximum analogWrite value is 1023 rather than 255 for some other Arduino boards, but I believe the principal is just the same.
I'm driving 3 LEDs directly from 3 outputs via current limiting resistors.
When I turn them on using analogWrite(PIN, 1023) they are not quite a bright as when the same LED is driven by the same pin using digitalWrite(PIN, HIGH). Which leads me to think that either 1023 does not give a 100% duty cycle or the maximum voltage in the analog case is less than that in the digital one.
Is this to be expected? Are the pins significant (4,5 and 14)?
Another similar Q&A would lead me to believe they should be the same.

I can confirm that 1023 does indeed give 100% duty cycle. I connected an output of my D1 Mini to my oscilloscope and got a steady voltage.
I can also confirm that the same voltage is output for digitalWrite() and analogWrite().
However the output drivers may not be the same. With analogWrite() it may be using a weaker output driver that can't deliver as much current, so the voltage droops slightly more than it would with digitalWrite(). However even with a 470Ω resistor connected between the output and GND (the smallest value I had easily to hand in a through hole variant) I see no variation in the voltage at all.
So if there is some variation then it might be some variable that is showing a variation in your specific unit but not mine.


(Beginner) Blinking led call function I'm completely new to this world, so probably my question would sound noobish, but here it is:

I'm trying to make a led blinking just for 5 times by calling a "for" cycle inside void loop(). The confirmation of the successful cycle would come from the Serial Monitor which will print "let's star over", and at the end of each blinking cycle, it will print the text "cycle done".

The point is that my code doesn't work, the led remain switched ON and the serial monitor blank. What is wrong with it?

int ledred = 3;
int count = 5;

void setup() {
  digitalWrite(ledred, LOW);
  pinMode(ledred, OUTPUT);

}

void loop() {

    blinkingred(ledred, count);
    Serial.println("let's start over")

}

void blinkingred(int ledred, int count)
{
  for(byte i=0; i == count; i++)
  {
        digitalWrite(ledred, HIGH);
        delay(1000);
        digitalWrite(ledred, LOW);
        delay(1000);
        Serial.println("Cycle done !");
  }
}

There's two things wrong with your sketch - one fatal and one that is more confusing for humans.

First the fatal problem:

for(byte i=0; i == count; i++)

That for loop is never going to do anything.  The way it is written it will loop only while i is equal to count (0 == 5) which it never will. Instead you need to loop while i is less than count:

for(byte i=0; i < count; i++)

The second issue is that you have named your function parameter variables the same as your global variables. While this is syntactically valid (the local variables will override the global ones) it is incredibly confusing for people to follow what is what and should be avoided at all costs.


How do I know the sampling frequency? I am beginning to get a bit confused about sampling rates and baudrates etc. I have this Arduino code:

#include <eHealth.h>

extern volatile unsigned long timer0_overflow_count;
float fanalog0;
int analog0;
unsigned long time;

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

void loop() {
  while (Serial.available()>0){
    serialByte=Serial.read();
    if (serialByte=='S'){
      while(1){
        fanalog0=eHealth.getECG();
        // Use the timer0 => 1 tick every 4 us
        time=(timer0_overflow_count << 8) + TCNT0;
        // Microseconds conversion.
        time=(time*4);
        //Print in a file for simulation
        //Serial.print(time);
        //Serial.print(" ");
        Serial.print(fanalog0,5);
        Serial.print("\n");

        if (Serial.available()>0){
          serialByte=Serial.read();
          if (serialByte=='F')  break;
        }
      }
    }
  }
}

Since there is no delay interrupt, what is the sampling rate/frequency? Is it based on the Arduino ADC speed? When I increase the baudrate am I increasing the sampling frequency or just the rate at which I send data over the serial port?

The Arduino ADC clock speed is set in ..arduino-1.5.5\hardware\arduino\avr\cores\arduino\wiring.c

Here is the relevant part

#if defined(ADCSRA)
    // Set A/D prescale factor to 128
    // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
    // XXX: this will not work properly for other clock speeds, and
    // this code should use F_CPU to determine the prescale factor.
    sbi(ADCSRA, ADPS2);
    sbi(ADCSRA, ADPS1);
    sbi(ADCSRA, ADPS0);

    // Enable A/D conversions
    sbi(ADCSRA, ADEN);
#endif

For a 16 MHz Arduino the ADC clock is set to 16 MHz/128 = 125 KHz. Each conversion in AVR takes 13 ADC clocks so 125 KHz /13 = 9615 Hz.

That is the maximum possible sampling rate, but the actual sampling rate in your application depends on the interval between successive conversions calls.
Since you read the result and send it through the serial port, you are getting a delay that increases as the baud rate decreases. The lower the baud rate the longer it will take to send the same length of data and the longer it will take to call the next ADC conversion.

The actual sampling rate in your application can be determined with the use of a debugger or a simulator, but an easier solution is to toggle a digital pin every time you execute a conversion and measure the frequency that the digital pin toggles at.


Why does command line BOSSA not recognize Arduino Due? Running Ubuntu 12.04.4 LTS (64 bit) I try to upload my code to the Arduino Due through the Native port. I have tried both the bossac that ships with the Arduino IDE (which is a modified version of BOSSA), and the master BOSSA branch.

Running this command:

sudo ./bossac -p /dev/ttyACM0

I get this error:

No device found on /dev/ttyACM0

However, it works perfectly inside the Arduino IDE.

What can the problem be?

from the IDE's menu you can activate the verbose upload (and compile) mode, that will print all the command executed; Probabibly what you miss is the necessity to open the serial at 1200baud, that will trigger the reboot and consequent bootloader's start ont DUE chip, and bossac need to find the bootloader. see autoReset

edit: i've now a pc with a physical Serial, so i've tryed to upload in verbose mode:

Sketch uses 10,380 bytes (1%) of program storage space. Maximum is 524,288 bytes.
Forcing reset using 1200bps open/close on port /dev/ttyS0
/home/xxx/arduino-1.5.6-r2/hardware/tools/bossac -i -d --port=ttyS0 -U false -e -w -v -b /tmp/build8035422101690460839.tmp/sketch_apr14a.cpp.bin -R

as you can see he is resetting the board by opening the serial at 1200, forcing the bootloader to start. You have to do the same on your script befor launching bossac. How this can be done depends on your OS

Please note that the reset is triggered by the 8u2 chip used as USB to serial adapter on the arduino board, so bypassing it by connecting through tx/rx pin (like using your own conversor, like in my example with hardware serial) won't work unless you do a manual reset at the right time


Powering arduino and 12V Fan from same supply I have found a relatively small 12V switching power supply that I want to build into my device, using it to power both the Arduino Pro Mini and a couple of 12V cpu fans.

Am I correct in assuming that I can have the Arduino RAW pin and Fan+ on the same power supply lead? Or do I need to protect the Raw pin in any way? Also, I need to power 2x cpu fans, can this be done with one transistor or do I need one for each fan?

If I stay within the Current specs of my supply (6A) could I keep adding other 12V components on the same +lead as in the diagram below?

The board will take 12V, but the regulator will have to dissipate (as in heat) the excess power.

However, how much do you trust your power supply to not exceed the 12V?

The same applies to the other loads.

About max current, you should do the math for both typical case and peak case. Ex: the fan will draw much more current if for any reason it is stopped.

If you use only 1 transistor, you will get both fans to behave in the same way, because you will be using only 1 control line. Is this what you want?


Verify RGB Led Cube equipment I'm preparing this kit on eBay to create the following instructable - http://www.instructables.com/id/4x4x4-RGB-LED-Cube/
But I have doubts about 0.1uF and 22pF capacitors since the once on eBay are 50v. Also MOSFETs - instructable uses IRF9531 but the ones I found on eBay are IRF9540N.
Is the equipment I added on eBay compatible with instructable?

Capacitor ratings don't really matter in your case, as you are using only 5 volt. Only their values (F) do.

Though the crystal you selected has an indication it needs 20pF load capacitors, not 22pF. 22pF is probably still fine. (Also note the ±20% accuracy, so between 17.6 and 26.4pF)

The IRF9531 and IRF9540N have the same pinout. They are also pretty similar in specs. The IRF9540N is slightly better even.

Note that the ATMega328p doesn't have the bootloader pre-installed. It's not that hard to do yourself though.

The EEPROM you selected is an SMD version. Kind of hard to work with if you are still a beginner. Better use a DIP version instead (that one is a bit more expensive, but 4 times the size)

I'd suggest you add an USB to Serials Adapter to the list, so you don't need the Arduino Uno every time you want to reprogram it, and use the Uno for something more useful.


How do I print multiple variables in a string? Say I have some variables that I want to print out to the terminal, what's the easiest way to print them in a string?

Currently I do something like this:

Serial.print("Var 1:");Serial.println(var1);
Serial.print(" Var 2:");Serial.println(var2);
Serial.print(" Var 3:");Serial.println(var3);

Is there a better way to do this?

ardprintf is a function that I hacked together which simulates printf over the serial connection. This function (given at the bottom) can be pasted in the beginning of the files where the function is needed. It should not create any conflicts.

It can be called similar to printf. See it in action in this example:

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

void loop()
{
  int l=2;
  char *j = "test";
  long k = 123456789;
  char s = 'g';
  float f = 2.3;

  ardprintf("test %d %l %c %s %f", l, k, s, j, f);

  delay(5000);

}

The output as expected is:

test 2 123456789 g test 2.30

The function prototype is:

int ardprintf(char *, ...);

It returns the number of arguments detected in the function call.

This is the function definition:

#ifndef ARDPRINTF
#define ARDPRINTF
#define ARDBUFFER 16
#include <stdarg.h>
#include <Arduino.h>

int ardprintf(char *str, ...)
{
  int i, count=0, j=0, flag=0;
  char temp[ARDBUFFER+1];
  for(i=0; str[i]!='\0';i++)  if(str[i]=='%')  count++;

  va_list argv;
  va_start(argv, count);
  for(i=0,j=0; str[i]!='\0';i++)
  {
    if(str[i]=='%')
    {
      temp[j] = '\0';
      Serial.print(temp);
      j=0;
      temp[0] = '\0';

      switch(str[++i])
      {
        case 'd': Serial.print(va_arg(argv, int));
                  break;
        case 'l': Serial.print(va_arg(argv, long));
                  break;
        case 'f': Serial.print(va_arg(argv, double));
                  break;
        case 'c': Serial.print((char)va_arg(argv, int));
                  break;
        case 's': Serial.print(va_arg(argv, char *));
                  break;
        default:  ;
      };
    }
    else
    {
      temp[j] = str[i];
      j = (j+1)%ARDBUFFER;
      if(j==0)
      {
        temp[ARDBUFFER] = '\0';
        Serial.print(temp);
        temp[0]='\0';
      }
    }
  };
  Serial.println();
  return count + 1;
}
#undef ARDBUFFER
#endif

**To print the % character, use %%.*

Now, available on Github gists.


SPP-C and HC-05 are they the same thing or something else? I was actually thinking to buy a cheap HC-05 module while I was searching I found a similar (think so) module It say it is a replace for HC modules.

Is it compatible with Arduino Nano and will it work same as the HC-05 module ????

In theory they are the same and have the same capabilities. Practically they are not. With SPP-C you get twice the headache for half the price as for HC-05. In had to find it out the hard way Sending data using Bluetooth SPP-C Module without a Breakout-Board. I tried both SPP-C and HC-05 with and without breakout boards finding the same issues. So if you are willing to spend time, risk your project and save some money then use SPP-C. Otherwise use the well known HC-05.


Converting data between baud rates This isn't strictly limited to Arduino but I spend a lot of time with serial devices on my Arduino and I'm sure that others do as well:

Here goes..

Let's say a device sends three characters [ABC] via serial at 9600 8N1.

And let's also say the device receiving the data only knows that it's serial stream and 8N1 but does not know the baud.

The receiving device would need to take a guess at the baud and so probably get it wrong. It would therefore receive weird characters.

Is there anyway/anything around that a user could paste the strange characters into that would reverse engineer (from the bit stream) to give the correct baud and hence correct ascii characters [ABC]?

I am not aware of anything like that, no.  The problem is what you are seeing as characters are a complete corruption of the data. Only some part of it may have been interpreted as a valid bit sequence, and even then you can't know what bit it was.

However, there is one magic character in UART communication: U

What is special about that character is its binary pattern.  It is ASCII character 85, which in HEX is 0x55, or binary it's 0b01010101.  Add to that the start and stop bits, and invert it for the UART logic (1 = LOW, 0 = HIGH) and the signal that gets sent out of the UART looks like:

____start_____     _____     _____     _____     _____
    |   |  0  | 1 |  0  | 1 |  0  | 1 |  0  | 1 | stop
    -----     -----     -----     -----     -----

And yes, that's a pretty good square wave.  The frequency of that square wave will be exactly half the baud rate - so a frequency of 4800Hz will be a baud rate of 9600 baud.

This effect is cleverly used for a system called Automatic baud rate detection whereby a receiver waits for a U character to determine the baud rate to use.  Most modern microcontrollers have this facility available.

If you can't get the frequency of a block of U characters you will have to examine the waveform with an oscilloscope.  It should be possible to identify the individual characters in the data stream as distinct blocks in the waveform.  From that you can then work out the width of one symbol and thus the baud rate.  It's best to use a DSO for this since you can then capture a short burst and use the markers to measure the time between different points in the waveform.  A logic analyser will also do the job quite well, and will most likely be able to decode the waveform and calculate the baud rate for you.

If you have neither of those it would be possible to program an Arduino to capture the time between transitions of an incoming signal and allow you to plot them in Excel to give you a waveform you can examine to determine the baud.

Another option is just to keep trying different baud rates (there's relatively few "standard" baud rates) until you see the right text coming in.


nrf24l01 fried when supplying 6.5V to VIN? I have two Arduino Unos (One clone, one genuine) and I'm trying to make a remote and a base station. Got everything working flawlessly, (Using RF24 library) and the last piece of the wiring was to get the remote Arduino off the USB and powered by battery. I have a 4 AA battery holder which I put 4 brand new alkaline batteries in. Soldered up some connectors, plugged it in and...nothing?

Ran the demos everyone seems to use. Nothing again. Ran the "diagnostic script at the end of that thread...results seemed fine...

CheckConnection Starting

FIRST WITH THE DEFAULT ADDRESSES after power on
  Note that RF24 does NOT reset when Arduino resets - only when power is removed
  If the numbers are mostly 0x00 or 0xff it means that the Arduino is not
     communicating with the nRF24

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x4c
RF_SETUP     = 0x07
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

AND NOW WITH ADDRESS AAAxR  0x41 41 41 78 52   ON P1
 and 250KBPS data rate

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0x4141417852
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x20 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x4c
RF_SETUP     = 0x27
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 250KBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

Ran test on the working arduino, and got a similar result. Checked continuity on all pins twice. Can't think of what could have suddenly gone wrong? Definitely didn't change my code, but just to be sure tried the examples from the above thread...

The only thing I did different was supplying power from VIN at 6.5 V (Measured with multimeter). Should be well within range for the linear voltage regulator? Definitely correct polarity. Hooked in a servo and wrote a quick sketch to drive it then powered the PWM from the battery powered arduino. Other function from my code (rotary encoder, OLED, etc) all seem to be functioning perfectly.

Fried module?

EDIT

I was powering the module through the 3.3V regulated output pin on the Arduino.

Noticed with the battery plugged in whenever I check the voltage with my meter 3.3 pin bounces to 3.7 then settles to 3.3. Not sure if that's the meter, or just the regulator catching up to the (what should be very low with a multimeter) load. Same behavior occurs with USB.

If I remember correctly (IIRC) The nrf24l01 module:

runs on 3.3 Volts
doesn't have a voltage regulator

It could be fried, try supplying a regulated 3v3 supply and see if it works then.


USB mini type B port on Arduino Uno I bought today an Arduino Uno R3, and I'm looking forward to make it an HID device. I have seen many projects using a serial USB type B port. As I want to build a little gamepad, I would like to use the smaller USB mini type B port to achieve similar results. Looking it up did not seem to bring significant results.

Am I missing anything? Do I have to use a serial port similar to the one used by Arduino or can I reproduce the project using the aforementioned port?

It sounds like you are going to be attempting software "bit-banged" USB.  That, while possible, is severely frowned upon, especially when you have the resources to do it properly at your fingertips.

In answer to your question, yes, you can use a USB mini B connector.  It is no different to a USB B connector except it is much smaller and contains one extra pin - USBID - which you can completely ignore (it's only used on USB On-The-Go devices).

USB is quite a heavy protocol to do in pure software - it won't leave much "room" for you to do much else.  Better would be to re-program the ATMega16U2 chip that is used for the current USB interface.  You will need some form of hardware programmer for it - you can use another Arduino Uno, and once done you won't be able to directly program the ATMega328P chip through the USB, so you would need some other method for connecting that (external USB serial adapter cable, or another Arduino), but the ATMega16U2 chip is specifically designed to work with the USB.  Offloading the USB portion of your project onto that chip and using the serial interface that is already wired up to communicate commands and instructions to/from the ATMega328P would be a much more powerful (and reliable) system.  There's plenty of tutorials and links around to show you how to reprogram that chip.


i am not able to figure out the problem due to which i can't upload my sketch to nano this is the error code (it is new from the previous time i posted)
i am using the hourly build for this and not the Beta
avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x6e

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x6e

this is the info of the loader and board i am using

Another idea - try using Windows Filemanager to navigate down through the folder path shown in the error message and see if the avrdude.conf file exists in the specified place. this probably will not solve your problem but it might help to understand what is happening. Good luck - Bob


What type of power supply is the Arduino Due’s 5v pin and what is its current? I’m looking to use a Futaba Servo with my arduino Due and was told it requires a “high current 5 volt supply” and I don’t know much about current so excuse my arrogance.
I know the arduino Due has a 5 volt pin. But what type of power supply is it? (Linear power supply, switching power supply, etc.) and how much current does it provide? If I get this information to my instructor he can tell me if it will suffice.

Thank you!

An Arduino should not be used as a power supply for a servo. The 5V pin is connected to the the 5V supply of the USB connector, OR to the output of a step-down buck regulator converting the DC barrel jack to 5V.

None should be considered "high current" for servo or motor use.

Most PC USB ports will max out at 500mA current output unless the device connected asks for more from the PC. The Arduino does not.

The buck-converter controller chip is a LM2434, whose datasheet specifies 1A maximum output current.

Driving motors or servos will draw enough current, intermittently, to overload either of those and will likely cause the Arduino to reset.

If you need to power a motor-type device, power it separately from the control signals. Power should go from the source to the motor, and the control signal from the Arduino to the servo, making sure to connect the ground wires of all to each other (motor, Arduino, power source).


fading colors on a ws2812 strip I have a strip of 7 leds. its ws2812. Im starting them on blue. Next I want them to do a slow fade into pink. So all Im trying right now is to increment r.

I can get them to work one by one. But I need them to all fade together from blue to pink.

Ive moved my r++ loop around till I was cross-eyed. Still it didnt fade all 7 leds to pink all at once.

sometimes it would stay blue and do nothing sometimes fade to pink one pixel at a time.

How do I get all 7 leds to fade together?
Thank you.

#include <FastLED.h>
#define NUM_LEDS 7
#define DATA_PIN 6
#define BRIGHTNESS 45
#define COLOR_ORDER GRB
#define g 50
#define b 100

int r; //changed it to undefined

CRGB leds[NUM_LEDS];

void setup(){
FastLED.addLeds<WS2812, DATA_PIN, GRB>(leds, NUM_LEDS);

 }
void loop(){

this lights all leds to blue

  for(int x = 0; x < NUM_LEDS; x++){

  leds[x] = CRGB(r,g,b);
 }
  FastLED.show();
  delay(10);

this code should grab all 7 leds in NUM_LEDS store it in x

  for(int x = 0; x < NUM_LEDS; x++){

  leds[x] = CRGB(r,g,b);

Heres the problem area. I get no errors but it doesnt fade all 7 leds at a time.
Ive tried moving my code around but it either doesnt fade or fades to pink one led at a time. where should my 'for loop' for incrementing r be at?
Should I be changing rgb all at once using array?

//take r and fade it up to 254

for(int r = 0; r < 254; r++) {

  }
  }
     FastLED.show();
 delay(100);

}

If you want to fade all the LEDs form blue to red at the same time, I think you want code like this (explanatory comments embedded)...

#include <FastLED.h>
#define DATA_PIN 6
#define NUM_LEDS 7

#define COLOR_ORDER GRB

CRGB leds[NUM_LEDS];

void setup(){
  FastLED.addLeds<WS2811, DATA_PIN, GRB>(leds, NUM_LEDS);

}

void loop(){

  // Let's take 256 steps to get from blue to red
  // (the most possible with an LED with 8 bit RGB values)

  for( int colorStep=0; colorStep<256; colorStep++ ) {

      int r = colorStep;  // Redness starts at zero and goes up to full
      int b = 255-colorStep;  // Blue starts at full and goes down to zero
      int g = 0;              // No green needed to go from blue to red

      // Now loop though each of the LEDs and set each one to the current color

      for(int x = 0; x < NUM_LEDS; x++){
          leds[x] = CRGB(r,g,b);
      }

      // Display the colors we just set on the actual LEDs
      FastLED.show();

      delay(10);
  }

}


Inappropriate ioctl for device I am using an Arduino Uno and a Mac and trying to upload my code into the board.
I tried uploading the program from different computers(MacBook Air and Pro) and I still have this problem.
How do I fix this? I tried downloading the FTDI driver. I went to the website that they suggested and tried following the instructions. I even followed other posts in Stack Exchange but I still cannot upload the code.
EDIT
Programmer -> AVRISP mkll
I am using a cable to connect to my Mac and I am using the Arduino software. The cable connected between the Arduino USB and Mac USB port.
I tried quitting and relaunching Arduino app. Once it launches I just press the upload button while my USB is plugged in. My available ports in the app are /dev/cu.Bluetooth-Incoming-Port and /dev/cu.Bluetooth-Modem
And this is the error
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1421": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

Plug your Uno into the Mac using a known good USB cable.
Go to the Apple menu -> About This Mac -> More Info -> System Report
Under the USB selection (on the left) please confirm whether or not you see something like this:

You can also open a Terminal window and type:
system_profiler SPUSBDataType

Amongst other things you should see:
USB:

    USB High-Speed Bus:

      Host Controller Location: Built-in USB
      Host Controller Driver: AppleUSBEHCI
      PCI Device ID: 0x3b34
      PCI Revision ID: 0x0006
      PCI Vendor ID: 0x8086
      Bus Number: 0xfd

        Hub:

          Product ID: 0x2514
          Vendor ID: 0x0424  (SMSC)
          Version: 0.03
          Speed: Up to 480 Mb/sec
          Location ID: 0xfd100000 / 2
          Current Available (mA): 500
          Current Required (mA): 2

            Communication Device:

              Product ID: 0x0043
              Vendor ID: 0x2341
              Version: 0.01
              Serial Number: 9314036423335121A0B1
              Speed: Up to 12 Mb/sec
              Manufacturer: Arduino (www.arduino.cc)
              Location ID: 0xfd130000 / 8
              Current Available (mA): 500
              Current Required (mA): 100

Note the "www.arduino.cc" entry.
In your Arduino IDE you should see the Arduino as a tty.usbmodemfd131 (or some similar number).

If you see all that it should work.
If not, please state in what way it differs.

Programmer -> AVRISP mkll

The Tools > Programmer menu selection is only used when you do Tools > Burn Bootloader or "Upload Using Programmer. It is completely ignored when doing a standard "Upload". You should be doing an "Upload" (Command-U) not an "Upload using programmer" (Shift+Command+U). So it makes absolutely no difference what you select from the Tools > Programmer menu.


Signal sampling: losing data every 103 points when it is recorded in SD I'm working on a system of acquisition and ECG datalogging with the Arduino, and I'm having the following problem:
I'm losing data every 103 points (just 103). No matter the sampling frequency to use, every 103 points, some points are lost, damaging the signal sampling.
It could be the recording time on the SD card, but even when the SD.close () command is run only once, the data is lost.
Here is a simple test algorithm with a 100 Hz sine wave at the entrance.

#include <SD.h>
#include <SPI.h>

int CS = 4;
int ECG_PIN = 1;
int voltage;

int index = 0;
const int bufferSize = 5;
int vetor[bufferSize];
int RECORD_TIME = 20000;
File logFile;

void setup(){
  pinMode(CS, OUTPUT);
  pinMode(ECG_PIN,INPUT);

  if(!SD.begin(CS)){
    return;
  }
  logFile = SD.open("ECG_log.txt", O_CREAT | O_WRITE);

}

void loop(){
  while(millis() <= RECORD_TIME){

      voltage = analogRead(ECG_PIN);
    if(logFile){

       logFile.println(voltage);

       delay(0.5);
    }
  }
  logFile.close();
}

What could it be? Speed analogRead ()? Problem on the SD card?

Sorry if the question is very basic, I am beginner, in a way, the Arduino platform. Any help will be very welcome.

Thanks!...

It's all to do with writing to the SD card.

You have a buffer of 512 bytes which is one "block" of the SD card.  When you have written to the card enough to fill that buffer up it has to write that buffer to the SD card and empty the buffer so you can start filling it again.

That writing to the SD card takes time - lots and lots of time (relatively), and it can't be doing anything else at the same time as writing to the SD card.

The only way you can get around that is to have your sampling performed within an interrupt - maybe a timer interrupt - so that it can interrupt the writing to the SD card.  However, that's not a simple task.

You would need to implement a system known as ping-pong buffers.  You have a pair of buffers for storing incoming samples within your interrupt routine.  When one buffer is filled up you switch to the other buffer and signal to your main loop() routine that you have filled the buffer.  It's then the job of loop() to save that buffer to the SD card and empty it ready for when the second buffer has been filled up.  The name ping-pong comes from the game of table tennis (also known as ping-pong) as you are switching from one buffer to the other and back again in a constant backwards-and-forwards motion like the ball in a game of table tennis.

Getting the right size of buffers is also critical.  You have to ensure that the time taken to fill one buffer is always going to be longer than the longest amount of time it takes to write a buffer to the SD card, including any flushing of the internal SD card buffer.  The best size is probably going to be to match that internal SD card buffer so every ping or pong you will be doing an entire SD card block's worth of data - so 512 bytes.

That means you have 3 buffers of 512 bytes - your two ping-pong buffers and the SD card's buffer, which is 1536 bytes - not far off the limit of an Uno, so you may struggle with that.  For this kind of thing it is better to use one of the boards with a more meaty chip, like the Mega2560.

Also the line:

delay(0.5);

is meaningless.  delay() takes an integer value, so 0.anything is actually truncated to 0.  To delay for less than a millisecond you should use delayMicroseconds().


Arduino in-built LED is not turning off I have an Arduino Uno whose LED, which is connected to  pin 13, is not turning off and it always stays on, and it annoys me.

Touching any exposed pins turns off the LED after removing my hands from the pins it turns back on slowly.

However it works perfectly with the programs. This program does turn the LED off and it stays that way while the program is running.

void loop() {
  digitalWrite(13, LOW);
}

When I upload other programs that don't use pin 13 then it stays on again. How can I fix this?

If you don't tell it to turn off, it behaves "as it wants". If you don't write a 0 on its pin, how can you force it to stay shut down?

If you want it to be in an off state, force it: in your setup function write

pinMode(13, OUTPUT);
digitalWrite(13, LOW);

No need to refresh it every loop, just in the setup.


Removing Robot IR Arduino Library on Macbook I'm trying to use my IR receiver on my Arduino Uno Board.  First I need to remove my IR Robot library because it interferes with the IRremote library. On my Mac, I have gone into the Arduino/library folder, but the name of the library I have to remove is not there.

I cannot figure out how to remove this. Please help!!

The folder name is RobotIRremote.

It's actually not necessary to remove that folder, though that will solve your problem. A better solution is to change the folder name of the IRremote remote library so that the file named IRremote.h found in that library will be given include priority over the one found in the RobotIRremote library. This is better because you would need to remove the RobotIRremote library every time you update to a new version of the Arduino IDE. The Arduino IDE gives include priority to files that match the name of the library folder but unfortunately if you install the IRremote library manually it will tend to have the folder name Arduino-IRremote-master which causes the wrong file to have priority. So you just need to find that folder and rename it IRremote.

If you don't know where it is the library folder can be found by:

File > Examples > IRremote > AiwaRCT501SendDemo
Sketch > Show Sketch
Folder


Arduino can't multiply? I have a value I'm taking from a sensor module, which is 2500 when the sensor is facing a light source. This reads to my code and can be saved perfectly fine. When I try to find the weighted average of a set of values (2500*1000+2500*2000+2500*3000 etc), the Arduino comes out with very weird answers. For example

2500*1000=9632

If I just compute 2500*1000 on its own, the answer still comes out the same! The results come out negative if I use int so I switched to using double (just in case the values created were too big), this stops producing negatives as expected but the result is still like it is above.. I have no idea why.. any ideas?

2500 * 1000 = 9632 is exactly what you expect with 16-bit integers. You
should use long integers instead:

2500L * 1000L == 2500000L

Floats work also, but are more expensive:

2500.0 * 1000.0 == 2500000.0

although I do not recommend testing for exact equality of floats (it
works here because these numbers are exactly representable).


Does MFRC522 supports native SPI of Arduino Due? Does MFRC522 library support native SPI interface of Arduino Due?

By native SPI I mean this one:

I came here with this question because the initializer asks for 2 pins: SS and Reset:

MFRC522(byte chipSelectPin, byte resetPowerDownPin);

SS pin can be any, but what about Reset?

There is no reason why it wouldn't support the Due's SPI. It just uses the default SPI.h library as the interface.

The resetPowerDownPin can be anything you like. It is not part of the SPI protocol but specific to that library. It is just controlled with digitalWrite() internally.

If you don't want to use the functionality you can set it to MFRC522::UNUSED_PIN and it will be disabled.