How to conect multiple output pin from sensors to a single digital pin on a arduino Hello i have several power management IC that have an active low indicator for a fault, it would be a waste to dedicate a single digital pin for each of them. So i thought of  to interface them to a single digital pin. I do not need to know which of them has a fault, i just need to know that there is a fault.

How do i safely do this? and as a follow up question if the fault voltage is 5v and the arduino pins only take 3.3v how do i shift it down with minimal components. can i just add a resistor in series?

If the ICs output 5V and your Arduino is 3.3V, you can simply use one voltage divider at the Arduinos pin to divide the voltage down to 3.3V.

But there is still one important thing to connect them safely: You have to check, if the outputs of the ICs are driven actively high, when no fault occured, or if they simply use a pullup resistor internally.

A pin, that is actively driven high, does not have an overcurrent protection. So, if one IC would pull it's pin to low and the others are still high, a high current would flow between them, potentially destroying them. In that case you need current limiting resistors in series with the ICs (directly at the ICs, so that the resistors are between them).

On the other side, if the ICs output a high level through a pullup resistor, you are safe to connect them directly, as there can only flow a very little current through the pullup resistors. Often such a situation is called Open-Drain (passive high level through pullup resistors, active low level by driving the pin to low through a MOSFET, like used in a digital output pin). In that case you don't need the current limiting resistors.

EDIT: The datasheet of the ICs, that you linked to states that the fault output is an

  Active-low open-drain output

Also the example circuit shows an external pullup resistor. That means, that the fault pin is internally connected to a MOSFET, which will connect the pin to ground in case of a fault. Otherwise the pin is floating. The external pullup resistor will pull the pin state to a high level, when the MOSFET is not activated. This is good for you, since you can now simply use 1 resistor (one resistor is enough for all ICs), to pull the level up to 3.3V. Then you directly have the correct level for your Arduino and you don't need a voltage divider.


What will happen when I use an invalid pin number? Related to:
  What happens if there is a runtime error?

This question is similar to the one above, however this is an alternate situation:

int pin = 999;
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);

What would happen in this instance? The compiler might catch it but if you used a random number would the IDE catch it?

The compiler will not detect any error and the code will compile and execute. Hence, to see what happens we need to explore the behind-the-scenes magic. For a summary, skip to end.

The second line in your code is where the magic will happen and thats where we need to focus.

pinMode(pin, OUTPUT);

The portion of pinMode relevant to this discussion is:

void pinMode(uint8_t pin, uint8_t mode)
{

    uint8_t bit = digitalPinToBitMask(pin); //The first instance where pin is used
    uint8_t port = digitalPinToPort(pin);

    if (port == NOT_A_PIN) return;

//Do something
}

(The complete implementation can be found in wiring_digital.c)

So, here, digitalPinToBitMask seems to be using pin to compute an intermediate bit. Exploring further, digitalPinToBitMask is a macro defined in Arduino.h whose definition is this one-liner:

#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )

This weird looking one liner does a very simple task. It indexes the Pth element in the array digital_pin_to_bit_mask_PGM and returns it. This array digital_pin_to_bit_mask_PGM is defined in pins_arduino.h or the pin map for the specific board being used.

const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = {
    _BV(0), /* 0, port D */
    _BV(1),
    _BV(2),
    _BV(3),
    _BV(4),
    _BV(5),
    _BV(6),
    _BV(7),
...
};

This array has 20 elements in total, so we are out of luck. 999 will index a memory location in the flash memory outside of this array, thereby leading to unpredictable behavior. Or will it?

We still have another line of defense against runtime anarchy. Its the next line of the function pinMode:

uint8_t port = digitalPinToPort(pin);

digitalPinToPort takes us along a similar path. It is defined as a macro along with digitalPinToBitMask. Its definition is:

#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )

Now, we index the Pth element of digital_pin_to_port_PGM which is an array defined in the pin map:

const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
    PD, /* 0 */
    PD,
    ....
    PC,
    PC,
};

This array contains 20 elements, so 999 is again out of range. Again, this command reads and returns a value from flash memory of whose value we cannot be certain. This will again lead to unpredictable behavior from here on.

There is still one last line of defense. That is the if check in pinMode on the return value of digitalPinToPort:

if (port == NOT_A_PIN) return;

NOT_A_PIN is defined as 0 in Arduino.h. So, if the returned byte from digitalPinToPort happens to be zero, then pinMode will silently fail and return.

In any case, pinMode cannot save us from anarchy. 999 is destined to result in doom.

TL;DR, the code will execute and the result of this will be unpredictable. Most likely, no pin will be set to OUTPUT, and digitalWrite will fail. If you happen to have exceptionally bad luck, then a random pin may get set to OUTPUT, and digitalWrite may set it to HIGH.


Using 2 PING Senors at Once I am trying to get values for two ping sensors, but am not getting any returns, can someone help me edit my code?

Code

void setup()
{
  Serial.begin(9600);
  pingRange(2);
  pingRange(3);
}

void loop(){
}

  long pingRange (int pingPin)

{
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  return microsecondsToCentimeters(pulseIn(pingPin, HIGH));
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

There's one part of your code conspicuous by its absence:

pingRange(2);
pingRange(3);

You're calling the functions, but you're not doing anything with the returned value.  I think you meant to print that value to the serial interface...

Serial.println(pingRange(2));
Serial.println(pingRange(3));


I2C and softwareserial Attempting to make gps unit with screen. GPS unit communicates over serial (Adafruit Ultimate GPS Breakout) and I can get GPS data through USB to my pc with Adafruit GPS library softwareserial examples. The screen communicates over I2C (Sunfounder OLED-SSD1306 Module) and I can get display with Adafruit SSD1306 examples. However I cannot get both to happen simultaneously. Board is Adafruit Metro Mini 5v 16MHZ. GPS is using pin 8 for TX and pin 9 for RX. Display is using A4 for SDA and A5 for SCL.

If "Adafruit_GPS GPS(&mySerial);" is not commented the screen will not display anything. If it is commented the screen displays just fine. How do I get both to function simultaneously?

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET     -1
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8, 9);
Adafruit_GPS GPS(&mySerial);

void setup() {
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    for(;;);
  }
  display.display();
  delay(2000);
  display.clearDisplay();
  display.drawPixel(10, 10, SSD1306_WHITE);
  display.display();
  delay(2000);
  testdrawchar();
}

void loop() {
}

void testdrawchar(void) {
  display.clearDisplay();

  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.cp437(true);

  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }

  display.display();
  delay(2000);
}

The problem was indeed running out of memory (as suggested by Juraj). After finding smaller libraries I was able to get it to work together just fine.


Using Multiple identical sensors - Beginner I'm trying to make an interactive installation where I have 6 pressure pads that each control an Air Fan. The pressure sensors ideally will be on chairs.

I would like the changes in pressure to change the speed of the Air Fans.

What is the easiest way for me to do this? Can I do it with just an Arduino?

I haven't bought anything yet as I'm assessing what the best route is.

If you mean this kind of sensor:

The sensor is a simple microswitch with mechanical pressure switching point, which means your Arduino just needs to monitor 6 digital inputs. That is entirely possible.

The sensors would have one side connected to ground, and the other to a GPIO pin on the Arduino, with a pull-up resistor to 5V. Your code should just check each of the 6 GPIO inputs. If the pressure sensor is tripped, the input would be LOW, otherwise HIGH.


Mac Arduino IDE Connection to Min Seg (Mega 2560). No tty I own a Macbook running OS X 10.10.3 (Yosemite)

I own a Min Seg.
My Min Seg model is built on an Arduino Mega 2560.

Problem

When I connect the board to the Macbook,
using either of the Macbook's two USB 2.0 ports,
using either of two USB A to B cables,
the board lights up, but I am unable to connect
to the tty device using the Arduino IDE.

Tools --> Port offered:

/dev/cu.Bluetooth-Incoming-Port
/dev/cu.Bluetooth-Modem
/dev/cu.usbmodem621 (Arduino Genuino Mega or Mega 2560)

I was expecting to also see:

/dev/tty.usbmodem621 (Arduino Genuino Mega or Mega 2560)

If I unplug the board, the third listed option
from Tools --> Port disappears, as expected.

Verification 1

I opened the System Information utility application.

USB --> USB Bus -->Arduino Mega:

  Product ID:    0x0042
  Vendor  ID:    0x2a03
  Version:       0.01
  Serial Number: 75435353038351316281
  Speed:         Up to 12 Mb/sec
  Manufacturer:  Arduino Srl
  Location ID:   0x06200000 / 3
  Current Available (mA): 500
  Current Required  (mA): 100

Verification 2

I used the Sparkfun Terminal Basics wiki to check for the device.
I used the Terminal utility application.

ls /dev/tty.* offered:

/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/tty.usbmodem621

screen /dev/tty.usbmodem621 9600 offered a successful connection.
[A white screen, which allowed for exit using Control+A followed by Control+/]

Attempted Solutions

I tried several means from here:

I installed the FTDI drivers.
I ran sudo nvram boot-args="kext-dev-mode=1" in the Terminal application.
Is an alternative driver worth attempting, such as that listed here?

I also attempted to connect through Mathworks Simulink.
When setting connection options, the program states
that a cu device is expected, rather than a tty.

What you are seeing is normal.

In BSD (which is the OS that Mac OS is based on) a serial port has two distinct devices for two distinct roles.

The tty, or TeleTYpe interface is used for incoming connections, be that from a modem, serial terminal, whatever. You would normally run a process called getty on it to present a login prompt.

The cu, or Call Unix interface is used for making outgoing connections to other devices. Traditionally that was mainly other Unix servers through modems. Nowadays it includes many other devices such as an Arduino.

The theory is that when you try and initiate an outgoing connection through the cu interface it first checks that no-one is connected in through the tty interface and if the serial port is available it disables the tty interface so the listening getty process doesn't interfere with your call. Also the tty and cu interfaces deal with the modem control lines differently.

The Arduino IDE is merely honouring that system by only offering you the outgoing device in the port list. As far as the Arduino communication is concerned there should be no difference.


Can I program Arduino with Python? I know that I can program Arduino with python but is it possible to make every project, which can be completed by normal IDE?

I imagine you want to use python because you are already familiar with it, know your way around the syntax, etc. But I would advice against this line of thinking, because microcontrollers need a little more of "low-level" thinking (given the limited resources they generally have) and because of that, it's probably best if you learn some C/C++.

The arduino programming framework provides some not-so-low-level libraries and tools (like the arduino IDE itself) to make it easy for non-C programmers to learn C-like programming.

However, if you want to use python as a proof of concept or anything else, sorry about the misunderstanding! :)


How to access GPS location without internet I need to provide a basic geolocation service for my clients. I built a location service based on the phone geolocation. It works great, not a problem. My problem is that some of my clients don't have an internet connection.
I know there is a company like Geotab that can provide these types of services.
If I want to build my own (very basic one), how can I make my diy (Arduino based) GPS communicate with my web servers?

If you want to send data to a server on the internet, you will need an internet connection, or at least a connection to a internet gateway.
Which type of connection you use, and how you set up that connection, depends on distance, speed, and coverage you need.
Probably the most universal for your application, in the sense that it will work wherever a phone would work, is to use a GSM/GPS module with an Arduino. You can google around for such modules; there are many. Note that you will need a SIM card for every module you use.
The GSM-bit of the module can then be used as a modem to communicate with your server over TCP/IP. There are many examples showing how to do that on the interwebs, so I won't go there.
If this doesn't help you enough, please add more detail to your question and I will edit the answer.


What is the difference when an arduino has been unplugged vs when a serial port connection was closed? Using python code for a serial port connection to an arduino, it sends a value to the arduino, which then starts printing values to serial. The python code will print the value on the first or second run (if run soon enough after), but after that it won't read what's from Serial.println again. To get it to read again (whether I wait some time or not, like for the while loop to finish), the arduino has to be unplugged and plugged in again, why is that different than the serial port connection being closed by python? Here is the arduino code used,
int measured;
int counter = 0;
int maxnum = 10;

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

void loop()
{
  if(Serial.available() > 0)
  {
    while(counter < maxnum)
    {

        Serial.println("V");
        counter++;
        delay(100);

    }
  }
}

I know the value sent from python can be read because I added in code that reads from serial after checking if it's available and changed an output pin value, which works, even if the serial println is not read.
Edit: Since the answer is there shouldn't be a significant difference and the arduino script should be reset if the serial port was closed, the issue should be with the python code.

We cannot know, if your python code also has a problem. But your Arduino code will send the series of "V" only once.
You are using this while loop:
while(counter < maxnum)

in there you are incrementing the variable counter. But after you left the while loop, you are never resetting counter to zero. So the next time, counter is still equal to maxnum. Thus the while loop will not run again. To solve that, insert
counter = 0;

directly after your while loop. Though, for such loops its normally easier to just use a for loop.

Also you might have a second problem. Currently the code waits for Serial data to be received. When something is received, the code will enter the
if(Serial.available() > 0)

statement. But this will stay true, unless you are actually reading the data. Currently the code inside the if statement will be executed on every loop() interation forever. So if you are applying the above fix to the first problem, the code will send "V" forever after you send the first byte to the Arduino. To actually only react to data being received, you need to read the data from the buffer - even if you are throwing the data away:
Serial.read();

What is the difference when an arduino has been unplugged vs when a serial port connection was closed?

For the Arduino itself? Nearly none. Reopening the serial connection will cause the Arduino to reset. The code then starts again from its beginning. Thats also what happens, when you power cycle (replugging) the Arduino. I think there are some little details, where both differ, but that certainly is not the problem here.
For the computer, replugging means, that the USB device (the USB-to-Serial chip on the Arduino to be precise) gets disconnected and again connected. That can lead to the OS allocating a different com-port/device-file for it, than before. Though that doesn't directly do something with the Arduino code (apart from the mentioned power cycle with reset).
For resetting (preserved from comment of OP):

I found that by setting DTR to 0 then 1, then 0 again, right before closing the port, the arduino resets.


Why is my "mood cue" not working? I am new to Arduino, and I am working through the "Arduino Projects book," with the Arduino Uno. I am working on project 5, "the mood cue." It is basically a potentiometer-controlled servo. I am certain that I have the code for it correct, and certain that I have all the wiring correct. I have the potentiometer value and the angle at which the potentiometer is turned printed on the serial monitor.

I upload the code, and the serial monitor begins printing correctly, changing when I twist the potentiometer. But the servo doesn't move. It lets off a faint buzzing sound, and that is it.

Does anyone know what the problem is? I don't know what I have done wrong. Do you think my servo is broken?

Here is my code:

#include <Servo.h>
Servo myServo;
int const potPin = A0;
int potVal;
int angle;

void setup() {
  myServo. attach(9);
  Serial.begin (9600);
}

void loop() {
  potVal = analogRead(potPin);
  Serial.print ("potVal:");
  Serial.print (potVal);
  angle = map(potVal, 0, 1023, 0, 179);
  Serial.print ("angle:");
  Serial.print (angle);
  myServo.write (angle);
  delay(15);
}

Here is my wiring:
file:///C:/Users/matth_000/Downloads/Arduino%20PotServ.jpg

The classic way of wiring up motors, including servos, is to provide them with separate power. The image below should clarify this:

The batteries (in this case) have the sole function of providing power to the servo motor. The "data" pin however goes to the Arduino.

The Arduino itself is powered by the USB cable in this example.

The important point is the blue wire - the shared ground wire. Both the Arduino and the servo (and batteries) must have a common ground.


Calculating location with 4 piezo's i've got the following problem i'd like to get solved and i'm breaking my head, so please help!

I have a rectangle with the following size 40 cm * 50 cm. On each corner of this rectangle I placed a Piezo element (it's an electronic element which measures the vibration)

The rectangle is defined as followed: the left upper corner = A the left lower corner = B the right lower corner = C the right upper corner = D

I'm trowing a ball on the surface and I'd like to calculate it's X and Y axis. The outcome of the piezo elements are as followed:

A,B,C,D - 0 lowest vibration, 1023 highest vibration These values can be mapped to a number I can decide, so that means I can make it whatever we need it to be. Example: map 0,1023,0,100, meaning the new mapping will be 0 - 100.

I found a possible solution here: http://mathafou.free.fr/pbg_en/sol114.html The problem I got is that i don't know where the ball will be and therefor I don't know the angle it will fall on.

The thing I do now is:

Example: We trow the ball. The outcome could be ABC or what would be best ABCD results.

I thought Pythagoras could come in handy here. The thing I did was: A*A+B*B=C*C (to get the square calculation done) A+B = AB, B+C = BC, A+C= AC, (to get the sides of a triangle) AB*BC=AC (We don't know AC but we can square root the outcome of AB*BC)

But then i realised I just know how long the side is and I still don't know where the ball landed :(

The following I already implemented to scale it when it works (maybe not relevant now) A+B+C+D = Total outcome we can possibly get at that point (as we are relying on vibration) A,B,C,D/Total = the scale we need to calculate with

I call this A1,B1,C1,D1 so I can re-use this in the code The reason I do this, is the follow up I need it for. Im going to use a projector to project a video on the exact X/Y position. But that's not relevant I guess for now.

I'm programming this in Processing 2 : http://processing.org

You might want to look into how LORAN works, as I believe you can do something similar.

First premise: You want to look for the initial transient caused by the impact propagating to sensors in various places on the periphery.  The signal in the material will end up bouncing around quite a bit before it dies out, but the leading edge of the initial transient should be unambiguous, so use that.

Second premise: You have no idea when the ball actually hits - you can also measure the difference in timing between when various sensors first detect it.

So take any two sensors, measure the time lag between when they detect the ball, and convert that via the speed of sound in your material.  This yields the difference in the distance of the impact point from the two sensors.  If you know the position of the two sensors, and plot the curves of points which satisfy the equation of the measured difference in distance from each of them you can a class of conic section called a hyperbola.

But so far you do not have an answer, but only a pair of curves along which the impact must lie.  So now take at least one new sensor, and repeate the exercise generation a new equation.

Combine the equations and solve to find the intersection of the curves - this is your point of impact.  It is possible to have more than one mathematical solution, but I think you will find that only one possible solution lies in the area between the sensors.

(Unfortunately, the ATmega328p A/D converter probably isn't fast enough to do a good job of this - at 10KSPS each sample is around 34mm in air, and around half a meter in typical solids - so you either need a much faster A/D, or else tune a comparator circuit to detect pulses and measure them with ATmega timer channels.)


WiFiEsp not working on Software Serial, working fine on Hardware Serial What I want to achieve

I want to connect to my wifi network using Arduino UNO and ESP8266 using WiFiEsp.h library over `SofwareSerial, since UNO doesn't have additional H/W serial.

What I am able to do already

I have a Mega, which I am able to connect to my wifi network(using ESP8266) using its hardware serial (RX1 and TX1), I've been following up this code example. Though it has code to deal with both cases( when H/W serial is present and when it's not) It doesn't seems to work on Software Serial on UNO, works perfectly on MEGA's H/W serial. I have made a little change in code as to set the Serial1 baudrate to 115200 as this seems to be supported by my ESP's firmware (1.54)

ERROR

[WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Cannot initialize ESP module

What I've tried

Tried running Software Serial on MEGA on pins 10,11 and 6,7 (Rx,Tx) (Same Error).
Swapping Rx,Tx :P
Changing pins to 10,11 instead of 6,7 on UNO
Switching Baudrate to 9600 on UNO (no help)

Yeah, Not much, but it seems so straight forward I can't figure out what could go wrong. It seems like it can't communicate to ESP, but why?

If you're going to talk to your ESP at 9600 baud - and that's about the upper limit for SoftwareSerial - you need to first change the ESP board's baud rate to 9600 baud. It is probably at 115200 right now.

You can do that with either kind of serial. Even though SoftwareSerial can't receive at 115200, it can usually transmit (Uno -> ESP) that fast. You need to send it the command:

AT+UART_DEF=9600,8,1,0,0

If you do it with SoftwareSerial, the reply coming back from the ESP after changing its baud will be garbled because your serial terminal will still be listening at the faster speed. So at this point, change the speed of your terminal and send the command:

AT

The ESP should respond with

OK

If it does - and it probably will - you're all set and can continue using it at 9600 baud. If not, go back to 115200 baud on your serial terminal and try it again. (I've never had to do it twice).

Update:

  I tried sending AT commands @ 115200, Its actually sending and receiving back well at 115200. Is this normal ?

With hardware serial, yes. The Uno's hardware UART can probably go at up to 4x that! But I've never had any luck receiving with SoftwareSerial at 115200; the most I could count on was 9600.


Input-Output Circuit Issue I have design a circuit with 2 led (red and UV) and 2 button.So, the circuit supposed to work like this:
If i press the button for red led, the red led lights up and the uv led turn off, and if i press the button for uv led the uv led lights up and the red led turn off.

But the circuit is not work like that, when i upload the code, the uv led suddenly turn on without touching the button.The red led had no issue.The red led turn on when the button is push.And turn off when the button is unpress.But when i push the red button, the uv led does not turn off.It stay glow.The uv led turn on whatever i push the button or not.

Here is the code :

int red = 8;
int uv = 9;
int redbutton = 2;
int uvbutton = 3;
int redbutcondition = 0;
int uvbutcondition = 0;

void setup()
{
  pinMode (red, OUTPUT);
  pinMode (uv, OUTPUT);
  pinMode (redbutton, INPUT);
  pinMode (uvbutton, INPUT);
}

void loop()
{
  redbutcondition = digitalRead(redbutton);
  uvbutcondition = digitalRead(uvbutton);

  if (redbutcondition == HIGH)
  {
    digitalWrite(red, HIGH);
    digitalWrite(uv, LOW);
  }
  else if(uvbutcondition == HIGH);
  {
    digitalWrite(uv, HIGH);
    digitalWrite(red, LOW);
  }
}

Try out this schematic. It will work.

So code will be :

int red = 8;
int uv = 9;
int redbutton = 2;
int uvbutton = 3;
int redbutcondition = 0;
int uvbutcondition = 0;

void setup()
{
  pinMode (red, OUTPUT);
  pinMode (uv, OUTPUT);
  pinMode (redbutton, INPUT_PULLUP);
  pinMode (uvbutton, INPUT_PULLUP);
}

void loop()
{
  redbutcondition = digitalRead(redbutton);
  uvbutcondition = digitalRead(uvbutton);

  if (redbutcondition == LOW)
  {
    digitalWrite(red, HIGH);
    digitalWrite(uv, LOW);
  }
  else if(uvbutcondition == LOW)
  {
    digitalWrite(uv, HIGH);
    digitalWrite(red, LOW);
  }
}


Keypad password check issue I am working on a school project, basically I have to create a lock system that opens a fictive gate when the correct code is entered. We have been asked to simulate our system before actually building it. So, I made the following circuit in Proteus(Labcenter Electronics' simulation software):

Here's what my system should do: A variable contains the correct code and the user must type a code on the keypad, and if it is correct, a green LED turns on and the LCD screen displays "Acces Granted!" if the code is wrong, the screen will display "Access refused!". It's a basic system, but I'm trying to make it as simple/short as possible(I have to explain it in an oral presentation, so the simpler the better) and for some reason, I can't get my code to work. Ideally, I'd like to have the LCD display a * for each character typed, liked on a real security system, but I haven't managed to do that either. I've been working on it for hours, trying different variants and etc.. but nothing seems to work the way I want to. BTW, my circuit works perfectly fine and the initialisation part of my code is therefore correct as well. Can anyone help me figure out what's wrong with my code and how I can make it better?

Here's my code so far:

#include <LiquidCrystal.h>
#include <Keypad.h>

//define LED pins
#define redLED 11
#define greenLED 10

String codeSerrure = "87362";   //correct code that opens the imaginative gate
String enteredCode = "";
int keyPressed;

const byte rows = 4;
const byte cols = 3;

char touches_digicode [rows] [cols] = {

  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins [rows] = {25, 26, 27, 28};
byte colPins [cols] = {24, 23, 22};

Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup(){
  lcd.begin(16, 2);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  digitalWrite(redLED, HIGH);
}

void loop(){
  lcd.setCursor(0,0);
  lcd.print(" Entrez le code");

  keyPressed = leDigicode.getKey();
  enteredCode += String(keyPressed);
  if(enteredCode.length() >= 5){
    if(enteredCode == codeSerrure){
      digitalWrite(greenLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces autorise!");
      delay(4000);
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, HIGH);
      enteredCode = "";
    }
    else{
      digitalWrite(redLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces refuse!");
      delay(4000);
      enteredCode = "";
    }
  }
  if(keyPressed == "#"){
    lcd.clear();
    enteredCode = "";
  }
}

The problem is that when I run this code in the simulation software, the LCD displays "Acces refuse!" and the red LED is on. No matter what keys I press (on the keypad) nothing happens. So the problem is that my code jumps straight to the else statement, inferring that the password typed is wrong (although no password was actually typed). I think the error is in here:

keyPressed = leDigicode.getKey();
  enteredCode += String(keyPressed);
  if(enteredCode.length() >= 5){
    if(enteredCode == codeSerrure){

Btw, forgive the french words, I am french. Also, I forgot to say, the # key should, clear the entered code. Any explanations, code samples or links would help.

The getKey() Funktion returns the define NO_KEY if no key was pressed, which is set in Keys.h as the NULL char (char with the value 0). In every loop cycle you are adding one character with value 0 to your string. But all functions, that handle strings, will stop, when they find a character with value 0 (it is the delimiter of C strings). Also a string with many NULL chars in it will not be matched to a string only consisting oft digits.

So you should check the return value of getKey for the NO_KEY define:

if(keyPressed != NO_KEY){
  enteredCode += String(keyPressed);
}

This avoids adding NULL chars to your string.


Made a Adafruit Flora unusable I was playing around with an Adafruit Flora and a strip of NeoPixel LEDs.  After uploading the sketch to the Flora (via Arduino IDE), the LED strip lights for about 1 second and then dims to a dull orange color for all the lights.  When this orange color appears, it seems to indicate that the Flora has crashed.  If I unplug the Flora from power and plug it back in, the LEDs light again for about 1 second and then it crashes again.

The time between boot and crash is short enough that I can't upload a new sketch.

So how would I go about rescuing the Flora?
Is there a couple pins I can jumper to put it into bootloader mode?  Or some other way of resetting the Flora so as to remove the offending code?

42 pixels in the strand all set to bright white.

This exceeds the power supply capability of either a USB port or the Arduino's regulator.

Likely the circuit starts out working, then once the LEDs are all on drawing high power either a protective device such as a polyfuse / PTC fuse activates trips or the supply simply sags under load.  At this point the circuit either shuts down or starts misoperating, the ATmega may go into brownout protection mode, etc.

Disconnect power to your LEDs and you will probably find that the Flora is fine.

You will need to use a suitable higher current power supply if you want to light more than a few pixels of this type at any given time.


"SSD1306 allocation failed" when #include SD.h I'm using the ssd1306_128x64_i2c example file from the 1306's library.

It works perfectly until I add the #include SD.h line, after which it gives the allocation failed error.

Please advise.

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <SD.h>

Adafruit_SSD1306 display(128, 64, &Wire, 4);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
  }

  display.clearDisplay();
  display.display();
  testdrawchar();
}

void loop() {
}

void testdrawchar(void) {
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.cp437(true);

  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }
  display.display();
}

I was able to make it all fit by using the text-only library for the OLED.

SSD1306Ascii Library

Much thanks to Majenko for explaining the problem and greiman for writing the library!


Interrupts inside a class attaching to the function of the class Hello i have a class and i would like to attach an interrupt inside the class and attach it to a function of the class.

class counter{
  public:

  counter(int pin){
    Ipin=pin;
  }
  void startCounting(){
    attachInterrupt(digitalPinToInterrupt(Ipin),this.addCount,CHANGE);
  }
  void stopCounting(){
    detachInterrupt(digitalPinToInterrupt(Ipin));
  }

  void addCount(){
    count++;
  }

  private:
  int Ipin;
  unsigned long count= 0;
};

Some what of the code above. There can be multiple intialization of this class. hopefully depending on the user uses a different pin.

There is a way arround this where the attaching of pin is done in the loop or setup and just calling a public function of the class. But to me that kinda doesn't fit the spirit of classes like a properly made library is done.

Im not very good at programming if you could teach me how it would be greatly appreciated.

I have a post about this problem.

Basically you cannot attach a class function with attachInterrupt because of the hidden "this" pointer which needs to be supplied to a (non-static) class function, where "this" is the particular instance of the class. You can work around it like this:

class myClass
  {
  static volatile bool switchChanged;  // declare

  public:

  void begin ()
    {
    pinMode (2, INPUT_PULLUP);
    attachInterrupt (0, switchPressed, CHANGE);
    }  // end of myClass::begin

  static void switchPressed ()
    {
    switchChanged = true;
    }  // end of myClass::switchPressed

  };  // end of class myClass

volatile bool myClass::switchChanged;  // define

myClass foo;  // make an instance of myClass

void setup ()
  {
  foo.begin ();
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

But that isn't great because, as you observed, you are really downgrading the class to use a static boolean.

Another way of doing it is to write "glue" routines, like this:

class myClass
  {
  volatile bool switchChanged;

  static myClass * instances [2];

  static void switchPressedExt0 ()
    {
    if (myClass::instances [0] != NULL)
      myClass::instances [0]->switchPressed ();
    }  // end of myClass::switchPressedExt0

  static void switchPressedExt1 ()
    {
    if (myClass::instances [1] != NULL)
      myClass::instances [1]->switchPressed ();
    }  // end of myClass::switchPressedExt1

  public:

  void begin (const byte whichPin)
    {
    pinMode (whichPin, INPUT_PULLUP);
    switch (whichPin)
      {
      case 2:
        attachInterrupt (0, switchPressedExt0, CHANGE);
        instances [0] = this;
        break;

      case 3:
        attachInterrupt (1, switchPressedExt1, CHANGE);
        instances [1] = this;
        break;

      } // end of switch
    }  // end of myClass::begin

  void switchPressed ()
    {
    switchChanged = true;
    }

  };  // end of class myClass

myClass * myClass::instances [2] = { NULL, NULL };

// instances of our class
myClass foo;
myClass bar;

void setup ()
  {
  foo.begin (2);   // pin D2
  bar.begin (3);   // pin D3
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

That's still not a great solution, but it might give you some ideas.

Your fundamental problem is that classes, by their nature, can be instantiated many times, however you only have a small, fixed, number of interrupts on the microprocessor.


Use of progmem in ESP8266 vs AVR and also how to handle large dynamic strings This is a somewhat tricky question dealing with implementation and best-practices of the ESP8266. I'd ideally hope that it's answered by people with in-depth knowledge on the problem.

As you are hopefully aware, the Arduino (AVR) platform requires the use of the PROGMEM or F() instructions to avoid copying all strings to RAM. The ESP8266 platform also provides a PROGMEM instruction, but is memory-mapped.

I thus have several questions about what the PROGMEM instruction actually does on the ESP8266.

For the next few questions, until otherwise marked, I am referring to character-array-style C strings, not the Arduino String type.

Storage of constant strings: If I were to declare a string (global, for now) on the ESP8266, would it be read from flash only when it's accessed, or will it always take up RAM (like it would on the AVR. Assume that in this case I do NOT declare it as PROGMEM; I wish to find out what the default behavior is on the ESP8266)?
Local Constant Strings: What happens with strings that are used inside a function? I am fairly sure that they ALSO exist in RAM, at least in AVR. Does the ESP8266 do this too, or does it (potentially) store it in flash until it is read (it is fine if it ends up inside a cache somewhere, as long as it can be evicted if needed)?
Use of String(F("mystring")): If I wrap a PROGMEM string in this manner, does this truly convert the string into a RAM-based string only when this line is reached, or does this for some reason initialize the String() early (and consume the RAM anyway)? Do the systems differ in this behavior?
If I define several instances of the above (as in, the identical wrapped string shown above appears several times, perhaps in different functions), do all of them point to the SAME F() instance (since they are identical) or does it get duplicated since it's part of code rather than a referenced variable? On ESP8266? On AVR?
On the ESP8266, I discovered that the server.on() function for the built-in webserver read F()'d constant strings just fine, but failed to work once the file grew beyond the size of the RAM. It was clearly stored correctly, but it could not be read. I thus conjecture that the method was making a local copy to RAM, even if the file was stored in Flash. There was also a on_P version that worked after that point (I believe I used PSTR rather than F at this point as well, since -- correct me if I am wrong -- the two are not compatible). Is this the real point of PROGMEM on ESP8266? That the data is only stored in Flash, but it also tells the function reading it to make as few copies as possible or chunk it?

I am also curious what happens with large strings that aren't constant. The web server can return data that was passed via querystring, for instance, which in my case can be quite large. If I copy that data to a string (and then into a function), does it pass the heap pointer directly, or does each String make a new copy? I am concerned about fragmentation or other fun ways of running out of RAM even if one copy should in theory fit.

Does doing something like bool myFunction(String &str){...} help? Some sort of way to actually ensure that it's the same string, rather than copying (and can I do String &myStr=server.arg(...) -- is a return value different from an assignment)? It's confusing for me, since strings are clearly passed by value, despite being a complex datatype with dynamic memory somewhere in there. So, did they override the assignment operator (and/or the one that handles reference passing, since I think there's more than one) to duplicate the string as pass-by-value of a basic type would normally do, or do they share pointers (and thus memory) as a class passed-by-value would normally do?

On the ESP8266 flash is a very special case. Because the ESP8266 itself does not have any flash, but instead uses an external SPI-connected flash chip, accessing it is not an easy or technically obvious operation.

Reading from the flash chip is slow. Very very slow (by comparison to reading RAM).  Because of this where possible certain things are copied into RAM. Also, there are different sections of RAM that are dedicated to different purposes.

dram0 - This is your "Data" RAM. It's where your variables and such are stored (80kB total).
iram1 - Instruction RAM. It's here that interrupt routines need to be stored for rapid execution (32kB).
icache - Instruction cache. 16kB of data that is cached when reading from the flash chip. Executed code usually gets copied here.

Normally when you execute code the block of code that the instructions you are executing are copied from flash into the icache memory block and then executed. This is reasonably fast (reasonably in that there may be brief delays while copying the data from flash, but fast when actually executing. I don't know how efficient the cache is, whether it's split into different blocks that are loaded in the background by the memory controller as needed, but it seems to be a pretty efficient system that is used in practice).

Because of this disassociation of the CPU and flash string constants, unless specified otherwise, will be copied into dram0 during startup. This makes it very fast and simple to get at the data. Anything that you don't specify as PROGMEM will get copied into dram0. Note that you don't get all 80kB of the RAM to play with since the SDK uses a portion of it. You only get about 50kB at most (station mode - softap mode will use more).

Now... what does PROGMEM do on the ESP8266 then?  Well, it adds an attribute to the definition that tells the linker to place the data in a specific section in flash (.irom.text.<filename>.<line>.<number>). This prevents it being copied into dram0 at startup.

So how do you get at it? That's where the *_P variants of the string functions (and certain overloaded functions in the Arduino core) come into play.

The whole of the flash chip is mapped (or can be, depending on register settings) into the ESP8266's memory map (address 0x40200000). Which means that it's possible to get directly at the data. However since this access doesn't go through the icache RAM block it's slow. Very very slow. About 12x slower by some accounts. Also because data can be in different locations within the chip the addresses of your string data can't be directly hard coded. There has to be some form of "it's over there" redirection when reading the data (for example if you use OTA updates you get two distinct blocks of flash where your code can be stored - the currently executing code and the previously executing version). The *_P variants of the string functions take that into account and look up where in flash the current code is located before reading from it.

So to summarise: Not using PROGMEM gives you fast access to your string data at the cost of RAM, and limits the size of the data you can use. Using PROGMEM removes the size restriction, doesn't use RAM, but is considerably slower.

To specifically answer your questions:

The string data gets copied to RAM at startup.
The string data gets copied to RAM at startup.
The string data gets loaded from flash (using *_P variants of functions) when the String object is constructed (RAM is allocated on the heap at that moment in time). The RAM is freed when the String object is destroyed (goes out of scope).
The compiler has recently had an update that will deduplicate constant PROGMEM strings.
As mentioned above *_P copies directly from flash and is slow, but has no size limitation.


Erratic behaviour using Serial.print() when powering only from power supply I'm using an arduino uno with a thermal printer and the following code:

#include "Adafruit_Thermal.h"
#include "skull.h"
#include "SoftwareSerial.h"
int printer_TX_Pin = 8;  // This is the yellow wire
int printer_RX_Pin = 9;  // This is the green wire
Adafruit_Thermal printer(printer_RX_Pin, printer_TX_Pin);

void setupPrinter() {
  printer.begin();
};

void doPrint(char* output) {
  Serial.print("Will print: ");
  Serial.print(output);
  Serial.print("\n");
  printer.println(output);
  printer.feed(2);
}

void setup() {
  setupPrinter();
  doPrint("This is a test to see if it will print only from power supply");
}

void loop() {
}

That code works fine if the arduino and printer are plugged into 5v and the arduino is also plugged in to a computer with USB. Once I remove the USB cable it starts printing:

This is a test to see if it will
This is a test to see if it will
This is a test to see if it will
This is a test to see if it will
This is a test to see if it will

over and over infinitely. In other programs it prints a slightly garbled first line then stops. When I remove the serial.print lines, this doesn't occur. Why would that be?

It seems likely that your Arduino is repeatedly resetting, which means it's starting the program again from the beginning all the time. This can be caused by insufficient power.

For the standard 5v Arduino boards, the minimum recommended voltage for an external power supply is usually 7v. An on-board regulator brings it down to 5v.

Technically, you can run them directly from an external 5v supply. However, you have to ensure that it's properly regulated, and that you bypass the on-board regulator.

Obviously you also have to ensure your external supply is capable of sourcing sufficient current. If you're just running an Arduino and a small thermal printer then it's probably OK, but it's certainly worth checking.


Where to store critical data in power outage situation on ESP8266 I want to store a counter that is always changing, but I want it to remain and being able to retrieve it on after a power loss.
It's only one long number data, but as it is always changing, I don't know where to store it to not over wear the memory space ?
I'm aware that writting to much on ESP's eeprom or SPIFFS would damage it.I've seen that post, but it doesn't help in my case.
The data to be saved is the volume of water pumped with a water pump during it's entire life.
Of course I could save it only once a while to reduce the number of writting, but I would loose some acccuracy.

If you worry about the maximum number of write cycles, you could write the data to an SD card or some FRAM connected to the ESP8266, or you could send the data to a (web) server (if you have access to one) using WiFi. The server can then store the data.
If you really care about the data, you could do both. Having a backup is the only protection against catastrophic failure.


Serial port usage in code I want to write a function that defines a serial port based on a flag but I'm not sure it's possible.
For example:
void writeToSerial(bool useSerial1)
{
   SerialPortClass serialPortObject; // Is there some way of defining a generic Serial port object and reusing it below?

   if (useSerial1)
   {
      serialPortObject = Serial1;
   }
   else
   {
      serialPortObject = Serial2;
   }

   serialPortObject.write("test123");
}

According to sources at c:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\HardwareSerial* (on Windows platform), you can use pointer to Stream class (because Serials are inherited from Stream).
So, your function could look like this:
void writeToSerial(bool useSerial1)
{
   Stream* serialPortObject;

   if (useSerial1)
   {
      serialPortObject = &Serial1;
   }
   else
   {
      serialPortObject = &Serial2;
   }

   serialPortObject->write("test123");
}


Multiple definition error when linking firmware.elf I just can't wrap my head around on how to properly work with multiple files. My code has been getting quite big so I decided to split all the classes into one file each. So I'm left with 6 files:

dataHandler.cpp
fileHandler.cpp
header.cpp
main.cpp
request.cpp
sensorData.cpp

header.cpp includes all the header files, and main.cpp the setup() and loop() functions.

Visual Studio Code shows me no errors while compiling. The includeguards have the name convention: CLASSNAME_INCG

So in my main.cpp for example I have something like:

#ifndef HEADER_INCG
#include "header.cpp"
#define HEADER_INCG
#endif

#ifndef SENSORDATA_INCG
    #include "SensorData.cpp"
    #define SENSORDATA_INCG
#endif

#ifndef DATAHANDLER_INCG
    #include "DataHandler.cpp"
    #define DATAHANDLER_INCG
#endif

setup()
{
    ...
}

...

When going into a class-file I have it defined in the following way (fileHandler.cpp):

#ifndef HEADER_INCG
#include "header.cpp"
#define HEADER_INCG
#endif

#ifndef FILEHANDLER_INCG
#define FILEHANDLER_INCG

class FileHandler{
    ...
}

#endif

So in summary I include the headerfile into every file, with includeguards arround. If I wouldn't include it I would get errors that crucial libaries like Serial etc. are missing. But when including the header into every file compiliing works just fine, but when it comes to linking the files togehter I get an error of multiple definitions.

So how can I define the headerfile just once for all files albeit I need it in every file?

Rule #1:
Header file extension is ".h". Files with ".cpp" are ususally compiled as separate compilation units into the object file. If you have any function definition (= declaration + implementation) or any global variable in more object files, it'll fail to link.
Rule #2:
No definitions in headers - variables and functions will cause this error if you include .h file into more .cpp files. If you need super global variable, you have to use declaration with extern modifier and you have to define it in one of the .cpp files. But only one! Also there can be only function prototypes (declarations) in header file. Implementation have to be only once in one of the ".cpp" files.

It's usually in the first chapter of books about learning C/C++.

Really short example:

// myLib.h
#ifndef _myLib_h_guard_
#define _myLib_h_guard_

void myFunction(); // function prototype (declaration)

extern int mySuperGlobalVariable;  // variable declared as extern, there must be definition somewhere

class MyClass {
public:
  int someMethod(); // method declaration

  int anotherMethod() { return 1; }  // definition inside of class works, but sometimes is less readable
};

#endif

// myLib.cpp
#include "myLib.h"

void myFunction() { // function implementation (definition)
  // do something...
}

int mySuperGlobalVariable; // definition

int MyClass::someMethod() { return 2; } // method definition

// main.cpp
#include <myLib.h>

int main() {

  mySuperGlobalVariable = 10;

  myFunction();

  MyClass instance;
  int first = instance.someMethod();
  int second = instance.anotherMethod();
}


Why is there no embedded c code in arduino libraries? When I took a look at how the arduino libraries were coded I expected to see register names like I/O registers(PINx,DDRx,PORTx) and other such registers with values assigned to them but instead I saw normal C code with functions and a class.

Why isn't there any embedded C in the structure of the library? Am I misunderstanding something very basic? Please help me understand.

If you take a look at the Arduino core library (e.g., the AVR version of
wiring.c), you will see lots of low-level register access. That's
why the core code is specific to a processor architecture.

Other libraries are built on top of the core API in order to be
portable.


Arduino disconnecting at upload This problem doesn't seen to be very common around the Arduino community.

Basically, what's happening is that as soon as I click the upload button, the Arduino IDE tells me that my Arduino board is not connected. What's strange though is that the python application ino is able to upload my code just fine, so my only guess is that there is something wrong with the IDE itself.

Here's a copy of the error message I am getting at the time of uploading the sketch:

  Binary sketch size: 444 bytes (of a 32,256 byte
  maximum)processing.app.SerialException: Error opening serial port
  '/dev/ttyACM1'.at processing.app.Serial.(Serial.java:178)at
  processing.app.Serial.(Serial.java:77)at
  processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:77)at
  processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:174)at
  processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)at
  processing.app.Sketch.upload(Sketch.java:1671)at
  processing.app.Sketch.exportApplet(Sketch.java:1627)at
  processing.app.Sketch.exportApplet(Sketch.java:1599)at
  processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)at
  java.lang.Thread.run(Thread.java:744)Caused by:
  gnu.io.UnsupportedCommOperationException: Invalid Parameterat
  gnu.io.RXTXPort.setSerialPortParams(RXTXPort.java:213)at
  processing.app.Serial.(Serial.java:163)... 9
  moreprocessing.app.debug.RunnerException: Error opening serial port
  '/dev/ttyACM1'.at
  processing.app.debug.Uploader.flushSerialBuffer(Uploader.java:101)at
  processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:174)at
  processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)at
  processing.app.Sketch.upload(Sketch.java:1671)at
  processing.app.Sketch.exportApplet(Sketch.java:1627)at
  processing.app.Sketch.exportApplet(Sketch.java:1599)at
  processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)at
  java.lang.Thread.run(Thread.java:744)

I am expecting to hear a few questions regarding this issue, so I'll go ahead and answer all the questions I can think of.

  Is this the first time you trying to connect to the Arduino from this computer?

No. In fact, I was able to upload the same source code just fine less than two hours ago.

  Did you try a different USB cord?

Yes, I did.

  Can you upload the source code from a different computer?

Yes, I can.

  Have you tried removing and reinstalling the IDE?

Yes, I have.

  Have you tried a different USB port?

Yes, I have.

What seems to be the problem here?

First of all, you must test if the device that you are trying to access, actually exists. The device file may change when you replug the Arduino. The easiest way to accomplish that is to find the device name in the error message, in this case /dev/ttyACM1. Then check two things:

Does the device file exist in  the /dev tree? ls -l /dev/ttyACM*
Is the Arduino IDE configured to use the correct device? Check under Tools => Serial Port.

Maybe another application is using the device. When working on Linux, you can verify this with the following commands:

$ lsof /dev/ttyUSB0
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF      NODE NAME
avrdude 7356   jippie    3u   CHR  188,0      0t0 266450197 /dev/ttyUSB0

or

€ fuser /dev/ttyUSB0
/dev/ttyUSB0:         7356

Where of course you have to replace /dev/ttyUSB0 with the device file as mentioned in the error message. In case of this question /dev/ttyACM1, but do notice that the number can change when you unplug the board for a moment and then replug it.

In both results, the 7356 is the PID of the process that is locking the device. In my example I was reading flash from the command line, so the output for your specific situation will be different. To identify the process, you can use:

$ ps -fp 7356
UID      PID  PPID  C STIME TTY          TIME CMD
jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i

or a more portable command:

$ ps -ef | grep 7356
jippie  7698 28116  1 20:34 pts/8    00:00:00 avrdude -patmega1280 -carduino -P/dev/ttyUSB002 -b57600 -D -Uflash:r:/tmp/flash:i


How to get a feedback that something connected to an Arduino is working? Assume you have an Arduino Uno board, the board is connected to some sensors, maybe a stepper motor or something, it does not matter.

How to get feedback or diagnostics or something that all the things are working, or if not then get feedback that are not working?

To expand on Juraj's answers, tackle this question from the user's point of view. What does all things are working mean for them? Does the temperature you read from a sensor have to be within .2C of a reference value? The stepper has to move a thing from defined positions A to B?

Based on the answers to questions like this, which is sort of a black-box testing approach, think about how to obtain reference values, then write tests in your Arduino to check if they are met. You might have to move your system into a defined testing stage first, like move the steppers to a defined starting point, then go test.


Where is the positive and negative holes on the arduino mini breadboard? I have the mini arduino breadboard. The pins go from A to J and 1 to 17. On the larger breadboard, there are symbols + and -. My breadboard doesn't have those two sections to put wires in. Does anyone know what to do?

Does anyone know what to do?

Do whatever you want to do.
There's nothing special about the +/- rails of a breadboard - they're just chunks of metal that go along instead of across, and are longer, with more holes, and someone has helpfully coloured them red/blue and added some symbols.
If you want a common place for + and - then just choose a common place for + and -.


Can I automatically loop inside a library? I want to write a little library;
the unlibrarized functionality does:

checking in every loop-cycle some inputs,
doing some calculations with it
and finally setting a boolean to either true or false.

How do I periodically check the inputs inside the library?
I know that I could add a function-call  to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

Is there a way, to instantiate a class and start an periodically function by doing so? And if, how does this constant checking affect/coexist with my 'normal' loop()-function?

Generally speaking, no, you can not take control of the processor away from the main "thread" in a library. The normal solution is to provide an update method or something like that. you could do the calculations in a function that returns your boolean answer, then the loop code is basically the same with or without asynchronous updating.

If you can use interrupts to read your input, either as an external interrupt or on an internal timer interrupt, then what you want could be achieved because the interrupt would take control away from the main execution context and give it to you.

Interrupt routines need to be fast and simple though, and it makes the "cost" of using the library higher, since there is a limited number of interrupts/timers and other libraries may require the one you code yours to use.

Of course, the more powerful arduinos that actually run an os will have support for multiprocessing which you could leverage to get the behavior you want. This answer is intended for a standard AVR based arduino (uno, mega, etc.)


Will the Arduino's low clock speed limit wireless transmission frequencies that are higher than the clock speed of the Arduino? I've recently used 2.4GHz and 433MHz wireless communication modules, and I was wondering if the Arduino can only process at 16MHz(Arduino UNO's clock speed), then won't the communication modules also be limited to a maximum 16MHz?

The frequency of a (wireless) radio is its carrier frequency. The data stream is carried on it by modulating that carrier wave in some way: by frequency-shifting, for example. A given processor could not provide data at a rate faster than its clock frequency (at least as a steady-state rate), but a packet of data, once supplied to and buffered in the radio, could then be streamed out at a speed unrelated to the physical specs of the supplier (the MCU). If the MCU had to drive the transmitter, bit-by-bit, then that would indeed limit the transmission speed.


How to connect ESP32 to HC-06? I am making a small project (BT controlled "tank") and need to connect ESP32 with HC-06 (ESP32 will be in controller and HC-06 in the vehicle). Android phone communication with both ESP and HC-06 works prefectly, I can not just figure out, how to pair/connect these two modules. Any ideas?

EDIT: Just to clarify, I can not connect them, because the HC-06 has PIN and I can not figure out how to remove that PIN or connect to it with PIN from ESP32...

You can either use a breadboard Or Female to Female Jumber wires.

Ofoucrse you can always solder yourself the two modules together with wires.

PS. Too low reputation to comment, so i insert this as answer


Send JSON via POST on SIM900 shield with AT commands I'm trying to send a JSON POST in SIM900 shield with AT commands. After I call the  AT+HTTPACTION=1 command, it returns a 601 error: +HTTPACTION:1,601,0.

I saw here that the error was 601 Network Error. Could someone help me? Following is my code.

void connectInternet() {
  if(digitalRead(9 != LOW)) {
    Serial.print("\r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print(" CONNECT ON INTERNET \r\n");
    Serial.print("------------------------------------------------- \r\n");
    Serial.print("\r\n");
    Serial.println("Connecting...\r");
    cmdAT("AT");
    cmdAT("AT+CIPSHUT");
    cmdAT("AT+CIPMUX=1");
    cmdAT("AT+CSTT=\"zap.vivo.com.br\",\"vivo\",\"vivo\"");
    cmdAT("AT+CIICR");
    cmdAT("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
    Serial.print("IP Device: ");
    cmdAT("AT+CIFSR");
  }
}

void send2Api() {
  Serial.print("\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print(" SEND TO API\r\n");
  Serial.print("------------------------------------------------- \r\n");
  Serial.print("\r\n");
  cmdAT("AT+CSQ");
  cmdAT("AT+CGATT?");
  cmdAT("AT+SAPBR=2,1");
  // Query if the connection is setup properly, if we get back a IP address then we can proceed
  cmdAT("AT+HTTPPARA=\"CID\",1");
  // Set the HTTP session.
  cmdAT("AT+HTTPPARA=\"URL\",\"http://api.com.br/endpoint\"");
  // set endPoint
  cmdAT("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  // set content json
  cmdAT("AT+HTTPDATA=100,5000");
  // POST session start
  // JSON payload
  cmdAT("{\"timestamp\":\"2016-03-08T19:36:45.000Z\",\"latitude\":\"-24.9458581\",\"longitude\":\"-53.4968357\"}");
  delay(100);
  cmdAT("AT+HTTPACTION=1");
  // POST session start
  cmdAT("AT+HTTPREAD");
  // Read the data of HTTP server
  cmdAT("AT+HTTPTERM");
  // terminate http
  ShowSerialData();

The PDP context setup is missing from your code. Many years ago I figured out that this initialization sequence works (i.e. extend your connectToInternet):

        //--if autobauding was enabled, send a blank AT
        command:='AT';
        send_gprs;

        //--switch to minimal mode - this is required to reset the SIM card
        command:='AT+CFUN=0';
        send_gprs;

        //--set dce speed
        command:='AT+IPR=57600';
        send_gprs;

        //--turn off command echo
        command:='ATE0';
        send_gprs;

        //--turn off command echo again - sometimes the first command is ignored
        command:='ATE0';
        send_gprs;

        //--turn on extended error messages
        command:='AT+CMEE=1';
        send_gprs;

        //--set module to full function
        command:='AT+CFUN=1';
        send_gprs;

Then it is very important to unlock your SIM card. The simplest solution is to disable PIN request (put your SIM to a real phone, and use the phone to set up this.) Verify if the module can proceed on SIM authorization:

        //--check pin
        command:='AT+CPIN?';
        send_gprs;
        //--right answer is +CPIN: READY
        //--wrong answer is +CME ERROR: 772

Then set up the APN. This will actually initiate an asynchronous APN request, and you shall not proceed until the AT+CSTT returns OK:

    repeat
        //--reset connection
        command:='AT+CIPSHUT';
        send_gprs;

        //--set GPRS APN
        command:='AT+CSTT="internet.vodafone.net"';
        send_gprs;
    until is_ok=1;

And finally, open a GPRS connection:

    repeat
        //--Open gprs connection
        command:='AT+CIICR';
        send_gprs;

        //--Get local address - for some reason this is required
        command:='AT+CIFSR';
        send_gprs;

        //--Suppress "SEND OK" after at+cipsend
        command:='AT+CIPSPRT=2';
        send_gprs;

    until is_ok=1;

(Ok sorry, this code is pascal and not especially golden, but you got the point about the sequence of the commands.)

Two very important things:

any command can fail - it is a good idea to send back the response to an AT command to your console window
AT+CIFSR is evil. If you don't use AT+CIFSR at the right sequence, the communication simply does not work. I was using SIM900D modules. Although you might feel it is optional to get your IP, actually it is not optional at all for some reason.

I was using AT+CIPSEND for the actual data communication. HTTP is so easy, and it is better to be in control.


Error: "'lcd' does not name a type" using LiquidCrystal library I'm following an online Arduino tutorial/course and trying to make a simple moving character on an LCD screen, but for some reason I get the following error: "error: 'lcd' does not name a type". I'm using the Tinkercad simulator because my PC's USB ports died recently.
Here's my code:

#include <LiquidCrystal.h>

byte character[8] {
   B01111,
   B01111,
   B01111,
   B00110,
   B01111,
   B01111,
   B01001,

} ;

  LiquidCrystal lcd(12, 11, 2, 3, 4, 5);

  lcd.createChar(0, character); //error is on this line

const int Lbtnpin = 6;
const int Rbtnpin = 7;
int Lbtnprev = HIGH;
int Rbtnprev = HIGH;
int pos = 0;

void setup(){
  lcd.begin(16, 2);
  lcd.clear();
  pinMode(6, INPUT_PULLUP);
  pinMode(7, INPUT_PULLUP);
}

void loop(){
  lcd.clear();
  int Lbtnstate;
  Lbtnstate = digitalRead(6);
  int Rbtnstate;
  Rbtnstate = digitalRead(7);

  if ((Lbtnprev == HIGH) && (Lbtnstate == LOW) && (pos > 0)) {
     pos--;
  }
  if ((Rbtnprev == HIGH) && (Rbtnstate == LOW) && (pos < 16)) {
     pos++;
  }
  lcd.setCursor(pos, 1);
  lcd.write(byte(0));
  Lbtnprev = Lbtnstate;
  Rbtnprev = Rbtnstate;
}

You cannot call methods outside of a function.
Move lcd.createChar(0, character); into setup.


Arduino Uno Rev3 Internal Quartz I'm using an Arduino Uno Rev3 Board and need to send a trigger signal at a certain frequency (20-50Hz).
This trigger signal should be as accurate as possible (+/- 0.01 ms).
The Arduino site states that the arduino uno has a 16MHz Quartz Crystal, but I'm measuring a frequency accuracy of about 0.35% (which would be typical for a ceramic resonator) instead of what i could expect from a quartz (0.001%).
I'm using the micros() function to measure time.
Am I doing something wrong? How is my frequency so inaccurate?

Thanks for your help! :)

Edit: Indeed when I have a look at the schematics, I see the ceramic resonator (Blue circle). However, there seems to be another 16 MHz part (red circle). could that be a quartz oscillator?

The ATMega328P chip is, indeed, clocked by a ceramic resonator. The website is misleading in stating that it has a crystal (I have emailed the webmaster to try and get this corrected, though I don't hold out much hope).

The 16MHz crystal in the schematics is part of the USB interface circuitry and has nothing to do with the timing of your running code. It is purely used to clock the ATMega16U2 chip which provides USB connectivity (USB requires a higher accuracy for stable communication).

There are other boards available with better crystals - most often boards that have native USB connections, such as the Arduino Due or Leonardo, or any of the myriad of boards by other manufacturers, like Teensy or chipKIT.


Writing a float to a BLE characteristic. What data format? I am currently working on a python-based Bluetooth Low Energy client for OS X and I got stuck while trying to write a remote float characteristic value.

First of all: my setup is an Arduino 101 with integrated BLE module and a Macbook. On the Arduino side the code is working well, I can read and write BLE characteristic's from a BLE explorer app on my phone.

Also I did achieve to read out the characteristics float values in my python script on the Macbook. Yet I did not fully understand what exactly I am doing. After requesting the characteristic's value from the peripheral, the peripheral answers and I get what I think is binary data? I could manage to unpack the data to a float by using.

     def characteristic_to_float(data):
        float_value = struct.unpack('f', data)[0]
        return float_value

The received floats are correct. But I couldn't get my python code to properly write a float value to the peripheral. I tried this:

    a_number = 5.3

    def float_to_characteristic(float_value):
        val = struct.pack('<f', float_value)[0]
        return val

    characteristic_1.write_value(float_to_characteristic(a_number))

The python code itself will run through without an error, but the Arduino doesn't receive the data. I am sure of that, because I implemented a function on it that sends out a Serial print when a characteristic has been written.

Remember the characteristics are read & write and I could verify this by using my phone. I think I got something wrong with the struct.pack thing, since I can't find any information about what data format is needed...

Does someone know how I can pack or convert the float to the right data format? Unfortunately the lib I use (Adafruit BluefruitLE) does not have a documentation.

Thanks!

Two solutions came to my mind if am gonna do your thing,
1) convert the number to a string char by char and send it as it is then unpack it as char by char , for example 5.3 -- > "5.3" it will be received then you have to decompose it 5 and . and 3 (inefficient solution because of conversion of types will be alot)

2) calculate the number of decimal digits and send it with the number something like:
5.3 ---> 53 and one decimal point, you would send it as
53:1 and then unpack it and reconstruct it

the second solution would be better for me since i have to send it as 2 things
number: decimal point
and then reconstruct it, this library will ease the reconstruction of decimal point sent by 53:1 (if you want to send floats in two directions)
SimpleSerialExtractor


Conflicting pins between the PCM library and speaker and the NRF24L01 The PCM library uses pin 11 and the NRF24L01 also uses pin 11. I am using an Arduino nano, and don't know if there is any way to change the pins of either the speaker or the transceiver.
https://github.com/damellis/PCM

No, you can't just change pins. Both systems use hardware that is specific to pin 11.
The best you could achieve would be to use a software SPI implementation on other pins to drive the nRF24L01, but that would mean changes to the library you are using to remove the SPI library usage and replace it with your own software SPI implementation.


How to use tinygps.h library to measure distance? using NEO6mv2 any reference site for the format code for tinygps.h to measure distance?
or any codes for tinygps.h for measuring distance i'm just a beginner in learning arduino thank you

You don't use the tinygps.h library to measure distance. You use the tinygps.h library to get coordinates. Over short distances those coordinates (longitude and latitude) can be equated to x,y coordinates on a plane (over greater distance - hundreds or thousands of miles - it gets a whole lot more complex).

Two sets of x,y coordinates form a line. A line is one side of a right-angled triangle (the hypotenuse).

Pythagoras (remember him from math class? That rubbish you thought you'd never need? Well, now you do...) says that the square of the hypotenuse is equal to the sum of the squares of the other two sides.

You know the other two sides - they're just the difference between the two x coordinates and the two y coordinates.

We're not going to write the code for you, and Google is probably better at finding websites with example code on than we are.


GPS module to a Bluetooth Transmitter I want to create a simple module in which a GPS transmitter moves and transmits positional data to the Arduino board via a Bluetooth Transmitter.
Basically, I need a two-piece bluetooth set, in which the transmitter is attached to the GPS and the receiver is attached to the Arduino UNO.
I would like for the GPS to be able to move from far away.

How would I do this? Does anyone know what products can do this? Would I use TinyGPS or a simple GPS module?

Thanks,
Mark

As u mentioned that u want to move your GPS far away .... but frankly speaking Bluetooth modules will not work for far away (I have used one of them , it has some limitations and restrictions) , they are good only for in the range of room only like 10 meters to 15 meters maximum . and in case any obstacle comes between the bluetooth devices , your device will lose its signals !
So better use SIM900A (it is wireless) , it cost a bit harder than bluetooth , but much better than bluetooth !


Help with my DHT22 sensor and using GET request For some reason using my DHT22 sensor I keep getting "NaN". I have tried using older versions of the DHT22 sensor library as suggested by a few of my searches, but it still doesn't fix the issue.

Also I can't get it to work with the GET request portion. Any help would be greatly appreciated.

#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <Phant.h>
#include <ESP.h>

#define DHTPIN 2
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Myyyyyyh";
const char* password = "Ixxxxx1";
const char* host = "script.google.com";

//*****example address
//https://script.google.com/macros/s/AKfycbyNsFc87GQmRP3GnWoTzK6/exec?tag=test&value=8
const String gardenchart = "/macros/s/AKfycbyNnWoTzK6/exec?";
const byte sleeptime = 1;
const byte NUM_FIELDS = 5;
const String fieldNames[NUM_FIELDS] = {"ghumidity", "gtemp", "light", "otemp", "wtemp"};
String fieldData[NUM_FIELDS];

void setup() {
  Serial.begin(115200);
  delay(10);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  fieldData[0] = 1;
  postdata();
  ESP.deepSleep(sleeptime * 60 * 1000000, WAKE_RF_DEFAULT);
}

void loop() {
  delay(50);
}

void postdata() {
  fieldData[0] = dht.readHumidity();
  fieldData[1] = dht.readTemperature(true);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect (host, httpPort)) {
    return;
  }
  for (int i=0; i<NUM_FIELDS; i++) {
    client.print("GET ");
    client.print(fieldNames[i]); client.print("&value=");
    client.print(fieldData[i]); client.print(" HTTP/1.1");
    client.println("Host:"); client.print(host);
    Serial.print(fieldNames[i] + fieldData[i]); delay(500);
  }
  client.println("Connection: close");
}

The Adafruit DHT library causes a shortcut on the signal line. That can be a problem for Arduino boards, but it is a big problem for the ESP8266.
Issue: DHT init sequence wrong #48
I don't know what is a bigger problem, the shortcut in the code or Adafruit not fixing it.

Why do you mention the Arduino Uno with a label ?
For the "GET" you should find a good working example.

The DHT22 is not very good. There are better sensors with a normal I2C interface, for example the HTU21D-F or the BME-280. This is about a great test: Hackaday: Humidity Sensor Shootout. The BME-280 is the undisputed winner.


What happens when there's no space left on SD card? I'm coding a data logger and I would like to know what happens if there are no bytes remaining to be written using SD library, ie, if the SD card is full of data. The logging would just stop or I would get some nasty error?

Open-source is just great. Lets have a look at the source code for SD. Here is what happens on write of a block.

/**
 * Write data to an open file.
 *
 * \note Data is moved to the cache but may not be written to the
 * storage device until sync() is called.
 *
 * \param[in] buf Pointer to the location of the data to be written.
 *
 * \param[in] nbyte Number of bytes to write.
 *
 * \return For success write() returns the number of bytes written, always
 * \a nbyte.  If an error occurs, write() returns -1.  Possible errors
 * include write() is called before a file has been opened, write is called
 * for a read-only file, device is full, a corrupt file system or an I/O error.
 *
 */

The source code shows that blocks are allocated from the free list and if there are no more blocks the function will return an error.


Help with struct variable I made a struct like this:

typedef struct {
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
} buttons;

and a variable like this:

button test[1] =
{
  {{0,0,0},{0,0,100,100},"getSomething",setSomething}
}

In loop() I call test[i].color, test[i].position normally.

Problems start when I want to execute a function.

I made two attemps, one with string and one with a function statement. With the string I have no problems using a strcmp() but it's not what I want.

I need to know how I can store 2 different functions in the struct and how I can execute.

Thanks in advance!

The typedef is no longer needed, using the 'struct' with a name declares the type.

// Arduino Uno

struct buttons
{
  int color[3];
  int positions[4];
  char init[20];
  void (*fn)();
};

// Declare the functions here, or use prototyping
void func1();
void func2();

buttons test[] =
{
  { {0,0,0},    {0,0,100,100}, "getSomething",  func1 },
  { {40,40,40}, {50,50,10,10}, "somethingElse", func2 },
};

void setup()
{
  Serial.begin(9600);
  Serial.println("Calling the functions:");

  test[0].fn();
  test[1].fn();
}

void loop()
{
}

void func1()
{
  Serial.println("func1");
}

void func2()
{
  Serial.println("func2");
}


Arduino esp8266 interferes with analog sensors UPDATE: I tried CNY70 sensor and the same error is valid for it too. Even outputs of CNY70 and LDR is the same while ESP8266 plugged in. I think ESP8266 interferes with all analog sensors

I connected my esp8266 and ldr sensor to my seeediuno (clon of arduino by seeedstudio) and ldr returns values like 70 110 105 120 etc. When I directly pointed light to ldr, return values don't change, value scatter randomly between 50-130. When I disconnect esp8266 and switch to arduino diecimila from ardunio ide, ldr sensor works fine. I think esp8266 somehow interferes with ldr sensor. How can I fix this problem?

#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
[![#define SSID "myssşd"
#define PASS "mypass"
#define BID 000001

const char *host = "api.host.com";

void setup() {
  //start serial connection
  Serial.begin(115200);
  //configure pin 2 as an input and enable the internal pull-up resistor
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
  pinMode(A0, INPUT);

  WiFi.begin(SSID, PASS);

  while(WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.println("Connecting...");
  }
  //If connection successful show IP address in serial monitor
  Serial.print("Connected to ");
  Serial.println(SSID);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP
}

void loop() {
  //read the pushbutton value into a variable
  int sensorValMeal = analogRead(A0);
  Serial.println(sensorValMeal);
  delay(1000);
}

This is how my serial prints looks like. You can see the anomally, I added my events as well.

Connecting...
Connecting...
Connecting...
Connecting...
Connected to Anaconda
IP address: 192.168.1.21
42 <- This is start
41
41
41
41
41
41
41
40
40
151 <- I turned my phones light to ldr
78
85
84
89
92
69
97
99
100
96
104 <- I switched of my phone's light
63
103
103
108
108
109
109
114
111
112
111
103
112
113
114
112
116
104
116
116
101
117
118
118
108
122
80
109
118
123
124
125
124
114
127
127
127
98
126
127
124
114
125
127
125
124
127
98
127
126
104
127
127
126
118
128
127
92
123
126
127
128
127
111
130

You read the analog pin of the esp8266, not the analog pin of the Seeeduino.


Lighting LED Strip via HC-06 Bluetooth Module What I Am Working With:
I am working on a project involving an Arduino, some RGB led strip, and my PC.

My Project:
The PC sends UART (serial) data to the Arduino over Bluetooth (through a HC-06 Bluetooth module connected to the Arduino) to change the color of the LED strip. The user could also change "lighting modes" to instruct the Arduino to make the LED blink, fade, etc.

My Problem:
Having no RTOS nor interruptions on data reception, it would be impossible for me to make the LED fade and, also, to receive Bluetooth data to change the lighting mode.

I would appreciate whatever input the community has regarding this problem.

Thanks in advance,
Stanislas.

Yes, it can be done. You don't need a realtime OS for something as simple as that. Basically in your loop function you would check the serial port and parse the input (if available) to see if the PC instructed the arduino to change its mode. Then you would call a function - say nextstep() - which would perform whatever the next step is, depending on your current mode. True, when you get serial input your loop() will take longer to execute, which will alter the 'rhythm' of your fades etc. If this is important, you should replace the call to delay() with a loop checking millis() against a value stored at the start of loop().

int currentmode ;
int previousmode ;

void loop()
{
   previousmode = currentmode ;
   currentmode = getnewmode(currentmode) ;
   if (currentmode != previousmode)
      initmode(currentmode) ;  // turn new mode on e.g. change LED color
   nextstep(currentmode) ;     // if current mode is dynamic, make change
   delay(DELAY_INTERVAL) ;
}

int getnewmode(oldmode)
{
   if (!serialpending()) // no serial input
      return oldmode ;
   return parseinput() ;
}


How to change i2c address for mpu9250? I'd like to connect 12 mpu9250 sensors to one arduino board.

I can't find documentation on how to change the addresses of mpu9250 boards. (i read through the reference ). Some tutorials talk about changing addresses for other device so i assume it is possible for mpu9250. I found this map of registers but can't figure out how to change the address.

I realize that mpu9250 might be too specific, so general guidance on how to solve these problems would be highly appreciated.

mpu9250 is similar to more popular mpu9150 and mpu6050. It is also known as GY-9250

Might be a little late, but you can string more than two of these on one I2C bus, with a little ingenuity.

You connect the AD0 pin of each MPU to a different I/O pin of the processor, then take low the address of the one MPU you want to talk to.

Then that MPU has one address, all the others have the other address, and being slaves will not respond.

Provided you don't have more than one MPU selected at once, works a dream.


Arduino for Weather and Air Monitoring: Casing and Power Source I am intended to use Arduino to measure Temperature and Humidity (DTH11) and Gases Grove Sensor (Multichannel). Due to weather conditions in UK, I would to get your advice how to shield all of them in water proof box? Do you believe that using Polystyrene is useful?
Any recommended power source?

I'd say, use a IP-54 protection plastic case. The IP is a standard, that tells you, how big particles can(not) come into the case.

About powering, depends, how often can you go and switch batteries.
If you can, you can plug the cable in the case - drill the hole through and use watertight silicone plug to ensure, it is water resistant.

In case of batteries - use some LiPo batteries with DC-DC converter to minimum voltage.
Maybe you could even add a solar panel or two for addional life extension of batteries.


Read serial 8 bytes from Arduino buffer I am fairly new to Java, but with a rather complicated question.

We are looking at reading some bytes coming in from an Arduino. The Arduino sends bytes in the form:

 Serial.print(Voltage1);
 Serial.print(voltage2);

Since these voltages are numbers of the format "1.62", two digits after the decimal point, the Arduino sends 8 bytes, 4 for each voltage.

Previously in a MATLAB test we managed that by making the inputbuffer=8, and then splitting the bytes by doing something of the sort A=buffer(1:4) B=buffer(5:8), and as such we could plot or read the signals from the Arduino.

Is there a way to achieve this in Java? At the moment we are creating an input stream, and we tried to limit that to a buffer of the correct size, but we do not get anything even close to the expected. Most of the time our input from inputstream.read() gives us negatives, but not even something that we can understand or work with.

I hope this is well explained, and I really wish someone knows how to deal with this problem.

The standard way of doing this is to use delimiters. Serial is a streaming protocol, you don't necessarily get data in fixed size chunks. Something suitable would be like:

<1.23,4.56>

Notice the delimiters "<", "," and ">".

The receiving end ignores incoming data until it gets "<". Then it reads until it gets a comma. Between those two are the first number. Then it reads again until it gets a ">". Between those are the second number. Now you validate that what you got are in fact numbers.

This allows you to easily expand in the future to larger numbers, and more decimal places, eg.

<42.213,674.50326>


Why am only hearing noise or no sound? Alright, there is something missing in the question, I was able to hear one sound of the files and the others apply to the question I asked and that is why I am wondering. what is happening!

Here is the code:

   #include <SD.h>                      // need to include the SD library
#define SD_ChipSelectPin 4  //using digital pin 4 on arduino nano 328, can use other pins
#include <TMRpcm.h>           //  also need to include this library...
#include <SPI.h>

TMRpcm tmrpcm;   // create an object for use in this sketch

void setup(){

  tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  tmrpcm.play("music.mp3"); //the sound file "music" will play each time the arduino powers up, or is reset
}

void loop(){

  if(Serial.available()){

    if(Serial.read() == 'p'){ //send the letter p over the serial monitor to start playback

      /* These are spkean Numbers */

     // tmrpcm.play("1-24bit.wav");
     // tmrpcm.play("1-16bit.wav");
     // tmrpcm.play("200-insane.mp3");
     // tmrpcm.play("music.mp3")       // Strangely this is the working perfectly with good sound
     // tmrpcm.play("200-standard.mp3");
        tmrpcm.play("200.wav");        // from https://evolution.voxeo.com/library/audio/prompts/numbers/index.jsp
    }
  }

}

Everything is good when I play this tmrpcm.play("music.mp3"); but the others I hear aliens sounds expect this tmrpcm.play("200.wav"); which I can hear the number two hundred but I feel the sound is 4-bit depth which very noisy. The files used in the code are here

For clarification previously, I thought it was amplifying issues which then I had to used LM386 but the sound was the same noise with tmrpcm.play("200.wav"); and later when I tried this tmrpcm.play("music.mp3"); I was shocked it worked perfectly like what I need it to be!  so I was curious I removed the LM386 and played this tmrpcm.play("music.mp3"); again and worked alright just maybe less volume.

As @Juraj mentioned it was solved by changing the setting and I was able easily to play the sound when I matched the setting to this file:

So, I could not create one from scratch matches above setting but I was able to convert existing sound through this site
which allowed me to convert with desire setting and here finally the exiting sound has matched the setting:


Arduino or XBee unique identifier? Is there anything built into the Arduino Uno or the XBee Pro 2 radio module that I can poll within my Arduino script to act as a unique identifier? Mac address or otherwise? If anyone has a code snippet that can do this it'd be extremely appreciated.

Currently my Arduino nodes are broadcasting only to my node.js server, but my server is broadcasting to all the nodes, so if they're all waiting to be assigned an identifier number through the handshake function I wrote, they all receive the same one. If I stagger powering them up this is avoided and they each get a unique ID, but I hope there exists a cleaner solution.

When programming the Uno's, you could write identifying values into particular EEPROM bytes.  To automate the process, write a development-system program to produce serial-numbered HEX files, with the serial number counting up each time the program runs.

For example, if you store IDs into byte 0x1E of EEPROM, the serial number file would look as follows when the serial number is 0x23:

:01001E0023BE
:00000001FF

The first line in the above file says 01 bytes of payload, stored at address 001E, record type 00 (data), payload byte 23, checksum BE.   See wikipedia's Intel HEX article for further explanation of HEX file format.  In brief, each time the serial number byte goes up by one, the checksum byte goes down by one.

To program a serial number byte into EEPROM from a file called SNfile.hex, issue a command like the following.

avrdude -p atmega328p -c arduino -P /dev/ttyUSB1 -b57600 -U eeprom:w:SNfile.hex:i

See the avrdude manpage for explanation.

In your sketch, use EEPROM.read(address) to read a unit's serial number.  For example:

#include <EEPROM.h>
byte mySN = EEPROM.read(0x1E);

[Note, regarding your question about  “anything built in... to act as a unique identifier”, I once spent quite a while looking for such a thing on Uno, Nano, and Mega2560 Arduinos, and found nothing.  I haven't looked at XBee radio modules for such data.]


How to Store 2 analogRead values and read using EEPROM for Arduino Uno? Trying to write 2 values coming from analogread(A0) and analogread(A1) by EEPROM.write  and retrieve the values by EEPROM.read. I tried the following sketch for each write and read. However, could not get the values. Any help please.

For writing to EEPROM:

#include <EEPROMex.h>
int addr = 0;
int array[] = {0, 0};
char a;
void setup() {
}
void loop() {
    array[0] = analogRead(0) / 4;
    array[1] = analogRead(1) / 4;
    EEPROM.write(addr, a);
    addr = addr + 1;

    if (addr == 512) {
        addr = 0;
    }

    delay(100);
}

For reading from EEPROM is:

#include <EEPROM.h>
int address = 0;
int value[2];
void setup() {
    Serial.begin(9600);

    while (!Serial) {
        ;
    }
}
void loop() {
    value = EEPROM.read(address);
    Serial.print(address);
    Serial.print("\t");
    Serial.print(value[0]);
    Serial.print("\t");
    Serial.print(value[1]);
    Serial.println();
    address = address + 1;

    if (address == 512) {
        address == 0;
    }

    delay(500);
}

See Reading and Writing Data Structures to EEPROM.

EEPROM.write(addr,a);

You can't directly write arrays. See the link for how to do it.

Example code:

#include <EEPROM.h>
#include <EEPROMAnything.h>

int array[2];
int addr=0;

void setup()
{
}

void loop()
{
  array[0] = analogRead(0)/4;
  array[1] = analogRead(1)/4;
  EEPROM_writeAnything(addr, array);
  addr += sizeof (array);

  if(addr >= 512)
    exit (1);

  delay(100);
}

Your posted code is a bit flawed anyway. You know EEPROM has a limited life? If you have a sketch that writes to EEPROM indefinitely you will wear it out.

My code above stops once it reaches address 512.


Why LED light delay is 5 second in arduino? My code :

int pin = 8;
int pout = 12;
int result=0;
void setup() {
  pinMode(pin, INPUT);
  pinMode(pout, OUTPUT);
}

void loop() {

  result = digitalRead(pin);

  if(result == 1)
  {
    digitalWrite(pout, HIGH);
    delay(1000);
  }
  if(result == 0)
  {
    digitalWrite(pout, LOW);
  }

}

I have set delay 1 sec but whenever i put high voltage on pin 8 The LED glow for 5 second. why?

How to set delay to none ? means whenever the pin 8 is HIGH the LED will glow else off.

The problem (likely) isn't in your code. You need to include a pull-down resistor in your electronics, so that when you remove the "high voltage" the residual charge stored in the pin due to its capacitance can be drained. Alternatively you can use the internal pull-up resistors, but then you'd need to invert the logic of the pin (high becomes low and vice versa) and instead of connecting "high voltage" you'd need to connect ground to activate the LED.


Is output pin set to LOW grounded If I do following:

pinMode(MYPIN, OUTPUT)
digitalWrite(MYPIN, LOW)

What will happen? Will this effectively ground MYPIN or output some low voltage?

This will effectively connect the pin to ground. Note that the connection is
made by a transistor that has a finite resistance. This output resistance is
not really specified, but from the curves on the “typical characteristics”
section of the datasheet you can infer that the typical value is about
26 Ω.

The only hard specification states that the OUTPUT LOW voltage
should be no larger than 0.9 V, as long as the pin is not sinking
more than 20 mA. C.f. the table “DC characteristics” of the
ATmega2560
datasheet.


Webserver with Arduino Yun without SD I'm trying to set up a simple web-server with Arduino Yun without an SD card, i.e via REST, if I understood it right (I'm new to some of these stuff). I want to be able to "get" data (sent by Arduino) through a jQuery script and show the user a formatted HTML page.

Here I provide you a simplified version of my Arduino sketch:

#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

const byte internalLED = 13;

YunServer server;

void setup() {
  pinMode(internalLED, OUTPUT);
  digitalWrite(internalLED, HIGH);     // Turn the led on to advise about bridge begin in progress
  Bridge.begin();          // Let's activate the Yun Bridge...
  ledBlink(150);           // ...bridge activation done (user sees a blink)
  // server.listenOnLocalhost();       // Listen for incoming connection only from localhost (no one from the external network could connect)
  server.begin();          // Let's acrivate the Yun server...
  ledBlink(150);           // ...server activation done (user sees a blink)
}

void loop() {
  YunClient client = server.accept();  // Get clients coming from server
  if (client)                          // Is there a new client?
  {
    client.print(77);                  // Send a "77" to client (e.g. browser)
    client.stop();                     // Close connection and free resources.
    ledBlink(500);
  }
  delay(50);
}

void ledBlink(int delayTime) {
  digitalWrite(internalLED, HIGH); // Turn (or keep) the LED on
  delay(delayTime);
  digitalWrite(internalLED, LOW);  // Turn (or keep) the LED off
  delay(delayTime);
}

My Arduino Yun is connected via WiFi with static IP (192.168.1.98) to the same network of my laptop, and they can ping each other. Right now, if I insert into my browser the address

http://192.168.1.98/arduino/whatever

I correctly receive a simple «77» (no quotes or \r\n)

But I cannot "get" it when opening the page get_test.html (which is on my harddisk, not in the SD):

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $.get("http://192.168.1.98/arduino/whatever", {}, function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
</script>
</head>
<body></body>
</html>

This is strange to me because this html code works if I change the address inside the "get" request with https://dl.dropboxusercontent.com/u/12389503/demo_test.txt which consists only of a «21» (no \r\n). The problem is I don't even receive the alert when the address is the IP of Arduino, but the board is receiving the request since I can see the led blinking once, as expected.
I'm running out of tests, any suggestion is welcome.

Whenever making ajax calls from/to different hosts (as your pc and the yun) you should use JSONP.