Programming the serial description Is it possible to program a custom description so that my python program can know exactly what USB port to connect to for that specific programming?

It should be able to find any board with that program so the best approach is if a custom description can be programmed with the active program being uploaded.

I want to make sure my setup can handle multiple Arduino boards and always know what USB to use for each specific use.

This finds a general Arduino device:

for port in serial.tools.list_ports.comports():
    if "Arduino" in port.description:
        print "Arduino device!"

But I want something like this:

for port in serial.tools.list_ports.comports():
    if "proximity_sensor" in port.description:
        print "My specific Arduino program!"

On a normal Arduino board, no, it's not possible from a sketch POV. With a Leonardo or similar ATMega32U4 based board it may be possible to give it a unique VID/PID combination, and even possibly custom manufacturer and product strings. You may be able to do it by creating a custom board definition in boards.txt (or maybe manipulation of the AVR core) - but I have never tried that sort of thing with Arduino, so I cannot vouch for how easy it would be.

However (shameless self-promotion coming here...) if you were to switch away from Arduino and use a chipKIT board like the Lenny (or any of the other chipKIT boards with a direct USB connection, such as the Fubarino boards) then it is possible to craft a completely custom USB profile from within your sketch, including VID/PID, Manufacturer and Product strings, and even what devices the board implements. For example:

USBFS usbDevice;
USBManager USB(usbDevice, 0xf055, 0x1234, "Espentech", "My Little Widget");
CDCACM USBSerial;

void setup() {
    USB.addDevice(USBSerial);
    USB.begin();
}

void loop() {
    USBSerial.println(millis());
    delay(1000);
}

Which results in:

[  661.328155] usb 2-1.2.7: new full-speed USB device number 10 using ehci-pci
[  661.458613] usb 2-1.2.7: New USB device found, idVendor=f055, idProduct=1234
[  661.458616] usb 2-1.2.7: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  661.458619] usb 2-1.2.7: Product: My Little Widget
[  661.458621] usb 2-1.2.7: Manufacturer: Espentech
[  661.458623] usb 2-1.2.7: SerialNumber: CK2660A05312F3
[  661.459181] cdc_acm 2-1.2.7:1.0: ttyACM0: USB ACM device


Stepper motor not working in Arduino 101 I am trying to connect a stepper motor ( this model exactly https://create.arduino.cc/projecthub/trduunze/grove-starter-kit-for-arduino-stepper-motor-driver-66471d ) in an arduino 101 but it does not work for some reason. I have tried connecting everything ast they tell in the website with no results:

And then I tried connecting directly to the board without using the shield, and still getting nothing.

The code I am using is this :

#include <Stepper.h>
int t =0;
const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;  // number of steps the motor has taken

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

void loop() {
  // set the motor speed:
  int motorSpeed = 15;
  if (motorSpeed > 0) {
    myStepper.setSpeed(motorSpeed);
    // step 1/100 of a revolution:
    myStepper.step(stepsPerRevolution / 25);
  Serial.println(motorSpeed);//print how fast the motor is going in the serial monitor
  }
}

Connecting the stepper motor and the driver, and launching the sketch in an arduino UNO board works perfectly, so I am really worried about that maybe the Stepper.h library might be different for the Arduino 101 but I couldn't find anything about that. I just have no idea why the project is not working in the 101 but working perfectly in the UNO. Any help or tips would be highly appreciated.

Cheers!

EDIT

After a lot of messing around, I have only been able to light up one led in the controller connecting one of the motor cables to GPIO5. None of the other GPIOS seem to work with the step motor controller.

After reading the Stepper library and searching for several, I saw that in an example using an EDISON ( I want to thanks to Guimficus for posting his code here: https://communities.intel.com/thread/99133) they changed the pinMode of the GPIOS they were using in the setup function :

pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);

And after adding that seems to work like it is supposed to work.

Cheers!


Arduino UNO IR blaster - storing codes in PROGMEM I've setup an IR LED on my UNO, with the IRremote library, and have the code working to control an RGB LED strip from certain serial input, however as i'm storing the Raw infrared data in variables, i'm running out of RAM very quickly, and haven't managed to get code working that stores the IR data in PROGMEM, then buffers it to RAM for sending.

The current working code can be found at https://gist.github.com/dan-r/71294eaf9fe2354f1a0c7c13fc5f3bcd, and i've tried setting the int arrays as statics in PROGMEM, but whatever I do, I can't figure out how to buffer them into RAM, or even directly send them with irsend.

The Arduino Uno can not read data from PROGMEM (data in flash memory) in the same way as reading data from ram, there are special functions to read data from PROGMEM.

Create a buffer in ram and use one of those special functions to copy the data into that buffer.

Start with the Arduino PROGMEM reference.
Nick Gammon had made a great tutorial about PROGMEM.
All the PROMEM functions are in <avr/pgmspace.h>

Is the array of numbers always the same length ? That would make the sketch a lot easier.

Then perhaps something like this:

const unsigned int irTable[9][67] PROGMEM = { { ... }, { ... } }

unsigned int irBuf[200];

i = ...   // number of command
memcpy_P ( irBuf, &irTable[i][0], 67 * 2);
irsend.sendRaw (irBuf, 67, ...);


Nested for loop used to evaluate a two dimensional array of integers I am trying to use a nested for loop to evaluate and change numbers within the two dimensional array. Basically these numbers are minutes, or hours. This function is meant to reset the button controlled numbers when they go above 23 (hours) or above 59 (minutes) and also from going below 0. The two dimensional array that I made also has three arrays that need to be skipped (P1[0], P1[2] and P1[10] because they do not contain any time variables. When I click the buttons and increment the numbers nothing unusual happens they just don't bounce back like they are supposed to.

Here is the two dimensional array:

int P1[][12] = { //0-10
  {0}, //MODE
  {0, 0, 0, 0,}, //TOD variables
  // OnHR, OnMin, OffHr, OffMin
  {0}, //DOW
  {0, 0, 0, 0,},  //Sunday
  {0, 0, 0, 0,},    // OnHR, OnMin, OffHr, OffMin
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},
  {0, 0, 0, 0,},  //Saturday
  {0, 0, 0, 0, 0,} // Temperature variables
  //Sensor, GreaterThan/LessThan, Temp, Buffer, State
};

Here is the for loop that doesn't seem to work:

void HrMinBounce() {
  int i = 0;
  int q = 0;

  for (int i; i < 10; i++) { //iterating down Plug arrays
    for (int q; q < 4; q++) {
      if (i != 0 || i != 2) { //non time arrays
        if (q == 0 || q == 2) { //hours
          if (P1[i][q] > 23) {
            P1[i][q] = 0;
          }
          if (P1[i][q] < 0) {
            P1[i][q] = 23;
          }
        }//End of hours
        if (q == 1 || q == 3) { //minutes
          if (P1[i][q] > 59) {
            P1[i][q] = 0;
          }
          if (P1[i][q] < 0) {
            P1[i][q] = 59;
          }
        }//End of minutes
      }
    }
  }
}

I have 5 of these arrays, so I was hoping to make one loop that could take care of all 5 at once. Here is my previous loop that works but I would have to copy and paste a whole lot to get the result without the extra for loop.

void MinHrLimit() {
  int i = 0;

  for (int i; i < 3; i++) {
    if (i == 0 || i == 2) {
      if (P1[1][i] > 23) {
        P1[1][i] = 0;
      }
      if (P1[1][i] < 0) {
        P1[1][i] = 23;
      }
    }
  }
}

if(i != 0 || i != 2){ //non time arrays

Let's see.

If i is 0 then that is true (it isn't 2)
If i is 1 then that is true (it isn't 0 or 2)
If i is 2 then that is true (it isn't 0)
If i is 3 then that is true (it isn't 0 or 2)

In fact that expression is always true. You probably want:

            if(i != 0 && i != 2){ //non time arrays

   void MinHrLimit(){
      int i = 0;

      for(int i; i < 3; i++){

You don't need the declaration of i there, because it is redefined in the for loop. In the for loop the variable i has an undefined value. You really want:

   void MinHrLimit(){

      for(int i = 0; i < 3; i++){


How can I interface HMC5883L compass board to a smartphone with OTG? Friends... I have an idea to attach the compass sensor (HIMC5883L) with my  android smartphone using arduino, but I don't clearly know how to do this. I mean I want to make an OTG compass for smartphone for map navigation etc.(Many Smartphones have compass but mine have not).  If anyone had do this or know how to do this, please guide me. Thanks!

A cheaply available USB OTG adapter cable (ask eBay) will connect the Arduino to the phone.

You can then connect the compass sensor to your Arduino and write a sketch to retrieve the data from it and send it through the USB serial connection.

Then you need to write some software for the phone to receive and interpret the serial data and display it as a compass.  That is unless you are happy just to have a simple text display (like the Arduino's Serial Monitor) with the compass information showing in it, in which case there is off-the-shelf software that would do that (search Play)


OOP vs Inline with Arduino I have been programming for quite a while now but I am new to Arduino and AVR Programming. The main question I have about programming these Micro-controllers is are there major differences in designing code in Object Orientated Classes vs the more traditional inline programming I have seen in many examples?

In other words in the world of Arduino/AVR Controllers are there any savings with Memory and Performance utilizing classes or visa versa?

Say for example we have a Class:

class SomeClass(){

private:
   int x;
   int y;

public:
   void foo();
   void bar();
}

SomeClass thisClass;
thisClass.foo();
thisClass.bar();

Would there be any performance or memory gains designing the program in a more inline fashion like:

int x;
int y;

void foo(){ /*** Do something ***/};
void bar(){ /*** Do more stuff ***/};

I tried doing some searches on Stack Exchange and Google but couldn't find quite the answer I am looking for the closest thing I was able to find was this Stack Exchange Question.

The reason I am asking about this is I have a project that needs to be as light as possible and I am not clear how I should be designing my program in this environment.

Edit

Thank you for the answers, this has shed light on things. There is one thing that I am not quite clear about.

Say you have a class that you are designing that utilizes the u8glib as follows:

class UserInterface{
private:
   U8GLIB_ST7920_128X64 Display;

public:
   UserInterface();
}

How would you get around using "Dynamic Memory" like:

UserInterface::UserInterface(){
   UserInterface::Display = U8GLIB_ST7920_128X64(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
}

The reason you can't find the answer is because the answer is both Yes and No.

For basic class stuff - defining your class with methods etc and instantiating objects from it - there's little difference in the end result compared with "vanilla" C.  The compiler's optimizations are so good now that performance is just the same. Yes, there may be slight increases in memory use since you're passing an extra pointer with each method call (instead of foo(int x) you have foo(MyClass *this, int x)) but that's so small as to not be noticeable.

The big differences come when you start playing with polymorphism and other advanced topics.  When start doing these complex programs the compiler is not always unable to work out which functions are required and which aren't, and it's not able to cut out the unused functions ("garbage collection"). So you may well end up with bigger code.

That doesn't mean slower code, just chunks of code that are hanging around that never do anything.

Of bigger importance is managing your dynamic memory better than you are used to.  Since there is such a small amount of memory the heap is very small, and as a result it gets fragmented very easily.  Dynamic creation and destruction of objects (new myClass, delete myClassObject, etc) is very bad.  Class objects really need to either be statically defined (in global scope is the most common) or temporarily allocated on the stack (local instances).  Otherwise you're asking for trouble - and the first you will know of it is strange things happening (no error reports or exceptions, you see...).


Not able to get response from esp using Arduino uno I am new to Arduino & ESP modules, here am trying to communicate with ESP-01 via Arduino UNO. I have gone through multiple websites for initial setup. But when i upload my code to UNO, ESP is not responding back.Below is the code i have used.

#include<SoftwareSerial.h>
SoftwareSerial ESP(0,1); // RX, TX
//ESP RX-->1(UNO) TX-->0(UNO)

void setup() {
// Open serial communications and wait for port to open:

    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }

   // Serial.println("Goodnight moon!");

    // set the data rate for the SoftwareSerial port
    ESP.begin(9600);

}

void loop() {
      ESP.write("AT\r\n"); //Normally ESP responds to AT command with "OK"
    while (ESP.available()) {
        char inData = ESP.read();
        Serial.println("Got reponse from ESP8266: ");
        Serial.write(inData);
    }

}

Source: Link of the url

My observation on this is

ESP is blinking blue light when i reset UNO
UNO TX onboard LED is blinking
when i am trying to do  Serial.println("Goodnight moon!"); it is printing
Serial.println("Got reponse from ESP8266: ");         Serial.write(inData); is not printing

My questions are:

Is there any need to flash ESP with Firmware or is it default enabled.(i have 3 esp's with me all of them not responding with above code)
If no need then what is the possible mistake i am doing.

Here is the screenshot https://i.stack.imgur.com/mOklg.png

Note: I haven't used breadboard for connection, directly connected UNO-TX -> ESP RX and UNO-RX -> ESP TX, 3.3v VCC and ground.In the above screenshot on upload nothing prints, only when i type something "Got reponse from ESP8266: " is printing

SoftwareSerial ESP(0,1); // RX, TX

Pins 0 and 1 are hardware serial on the Uno, used with the Serial object, these pins are used to communicate with your computer (e.g. Serial Monitor) via the USB-serial chip on the Uno.

There is absolutely no reason you should ever use SoftwareSerial with pins 0 and 1. If you want to use software serial then connect the ESP8266 to pins other than 0 and 1. Otherwise don't use SoftwareSerial at all, but be aware that using Serial to communicate with the ESP8266 and with the computer is problematic and can also cause issues when you try to upload to your Uno.


How should I customize UIPEthernet constants? I am using UIPEthernet to get an Arduino Nano to drive an ENC28J60 Ethernet Shield for a UDP-based application. I'm customizing a number of its #define parameters to change default settings to save space, but I'm not sure I'm doing it correctly.  It's clearly designed to facilitate per-sketch customization, but things aren't quite working for me, and I can't tell if it's me doing it wrong, or if the customization doesn't quite do what I'm expecting.

Specifically, the comments at the top of utilities/uip-conf.h say:

  uIP has a number of configuration options that can be overridden  for each project. These are kept in a project-specific uip-conf.h file and all configuration names have the prefix UIP_CONF.

So that sounds great - I've copied uip-conf.h into my sketch (into the top directory next to my other sources), adjusted it appropriately, and ... nothing changes.

Now, I'm #including <UIPEthernet.h> into my source files, and everything compiles using the Arduino IDE (v1.8.10). Looking in the library, I can see <UIPEthernet.h> includes <utilities/uipopt.h>, which in turn includes "uip-conf.h" (note the quotes). So I think it's intended to be picking up my local one. But it doesn't - it uses the original one from the library.

My understanding of #include "example.h" is that it looks for example.h relative to the current file location, (ie <utilities/uipopt.h>, so utilities/), so I'm actually seeing correct inclusion behaviour and now I don't see how this customization approach could ever work!

I tried adding the #include "uip-conf.h" to my own sources, and that sort of works for my sources, but of course doesn't affect the library .cpp files themselves which still see the original version.

I could probably drag the entire lib into my sketch and fix up the includes, but that seems like the wrong answer. It's extensively designed to be customizable. Do you know what steps need to be taken to do it please? (Or a pointer to some docs would be fine!) Thanks!

Creating a copy of the include file in sketch folder will not work. At library compilation the source files of sketch are not included. The "" for include is "search first in the same folder as the including file".
The project in the description of use of uip-conf.h is UIPEthernet. It includes the UIP library by Adam Dunkels and configures it with this file.

A project with UIPEthernet library can configure the library with options in uipopt.h. Most of the options in uipopt.h are defined as
#ifdef UIP_CONF_UDP_CONNS
#define UIP_UDP_CONNS UIP_CONF_UDP_CONNS
#else /* UIP_CONF_UDP_CONNS */
#define UIP_UDP_CONNS    10
#endif /* UIP_CONF_UDP_CONNS */

this allows to define the value on compiler command line as -D. Most IDEs enable to set project defines in project settings. Arduino IDE does not enable this yet, because it doesn't have a project configuration file.
With Arduino IDE you can add defines for platform or for board definitions with build.extra_flags in platform.local.txt or in boards.local.txt. Example for boards.local.txt for Arduino Mega:
mega.build.extra_flags=-DUIP_CONF_UDP_CONNS=20 -DUIP_CONF_MAX_LISTENPORTS=30
platform.local.txt and boards.local.txt must be in boards package folder nect to platform.txt and boards.txt.


Is it possible to program an Attiny85 with a USB-to-TTL converter? I currently use my Arduino to program Attiny85. As I have one of these USB-to-TTL adapters I am wondering if it is possible to program Attiny85 with it, to free up my Arduino. I know it is possible to program Atmega's with such a thing.

If it is in fact possible to use the converter as a simple programmer for Attiny's, how should I connect the converter to the Attiny?

Yes, it is possible.

Note that the FTDI chip (assuming that is what you have) can be accessed as either Virtual Com Port VCP or D2XX. Where VCP is the traditional method of using them as Serial Ports with avrdude calling "-c arduino -P COM3 -b115200". However the later D2XX method allows for the pins to be Bit Bang'ed.

One can see in this tutorial it is possible to call avrdude with a programmer of "-c ftdi". Assuming that the D2XX drivers are installed.

Where I see in the current releases 1.0.5r2 and 1.5.7's avrdude's config files that a programmer of type "avrftdi" is supported, as opposed to the article "ftdi"

However, that is not to say the IDE natively supports its. You will have to either call avdude manually. Or add the "avrftdi" to "\arduino-1.5.7\hardware\arduino\avr\programmers.txt" so that the IDE will be aware of it.

That all said I see "Tiny AVR Programmer" that are very in-expensive.


Water flow sensor unable to get readings I connected my "arduino(nano)" to "water flow sensor" and wrote a code which simply prints the readings like 0-1023 and tested it. First i got the readings but now i'm not getting it.

My code looks something like this.

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

void loop(){
 int vla=analogRead(2);
 Serial.println(vla);
 delay(1500);
}

and my connection.

  Sensor to Supply module
  Vcc -->  5v
  Gnd -->  Gnd

  Sensor to Arduino(Nano)
  Sig --> D2

Sensor to Arduino(Nano)
  Sig --> D2

Your connections are wrong.

int vla=analogRead(2);

is reading from analog channel 2, which is pin A2 on your Nano, not D2

D2 is not an analog pin and thus you can't use it with analogRead().


Arduino Libraries: Declaring variables as public? How come I never see any Arduino Library expose some of it's internal variables as public in the header file? I only see functions which are declared as public, while every variable is declared private.

Background: I want to write my first Arduino library. And I thought of making some variables of this library public, so that I don't have to call a function later on when I import the library.

E.g. I want:

#include MyLibrary
...
MyLibrary instance();
instance.avariable = 12345;

instead of:

#include MyLibrary
...
MyLibrary instance();
instance.setVariable(12345);

Classes are used to hide away the complexity of a certain task. The user of the class should not worry about how the library exactly works in the inside, but instead only worry about how it should be used. In many cases directly writing to a member variable can be not only convenient, but hurtful if a wrong value is set. If you instead use a function to set the variable, the author can add code to prevent wrong values from actually being written to the variable. Also there might be some other logic involved, that is not triggered, if you write directly to the variable. So - for the ease of use - the users might want the library to be responsible for this, not themselves.

If you write a library, you have thought about how it should be used. Hiding other ways away is a common way of leading the user through the usage. Ways of usage, that don't go along with the purpose of the library can be hided away to make the correct way clearer. A manufacturer of a saw doesn't give the user instructions how to use the wrong side of the blade, because it doesn't help you with sawing.

This does not mean, that you shouldn't make variables public at all, but only if it makes sense. For example: If you are defining a class, that just represents a point in a coordinate system without hooks to other code, it is totally OK to make the coordinates public. But if you defined the class, so that the point is directly shown on a display, you might want to change the position on the display, whenever one of the coordinates is changed. In this case you can use a set-function to trigger the display update, when a new value was given for the variable.


How to set a time out like Serial.setTimeout() for Serial.read()? I read a comment form here:

"Serial.setTimeout() sets the maximum milliseconds to wait for serial data when using Serial.readBytesUntil(), Serial.readBytes(), Serial.parseInt() or Serial.parseFloat(). It defaults to 1000 milliseconds."

According to the latest webpage,

"Serial functions that use the timeout value set via Serial.setTimeout():

Serial.find()

Serial.findUntil()

Serial.parseInt()

Serial.parseFloat()

Serial.readBytes()

Serial.readBytesUntil()

Serial.readString()

Serial.readStringUntil()

"

So apparently, there's no direct indication to set a timeout option for Serial.read().

How to set a time out like Serial.setTimeout() for Serial.read()?

You can't set timeout for read(), but you can use readBytes() to read one byte.

byte b;
int count = Serial.readBytes(&b, 1); // read one byte with timeout
if (count) { // 0 or 1
  Serial.write(b); //echo
}


Arduino-like ethernet only board? I don't think USB chip is more expensive than Ethernet chip. So, I expect there should exist a board like Arduino, but where USB is removed in favour of Ethernet.

Are there such boards?

Yes, there's the Arduino Ethernet. Available from Sparkfun for example


Receiving Multiple data on Arduino Serial I am writing a very simple code in Arduino Nano, in which I am reading data that I send on Serial. Here is the code snippet.

int incomingByte ;

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

void loop() {

    if (Serial.available() > 0) {

            incomingByte = Serial.read();

            Serial.print("I received: ");
            Serial.println(incomingByte);
    }

}

When I send 'A' , I receive the following output:

I received: 65

I received: 13

I received: 10

What is wrong with the working of Serial Port here?

You send a string "A"

However, to denote the end, a carriage line (code 13) + line feed (code 10) is sent.

So what is sent is actually an 'A' character followed by a return.
This way you also know when a new line starts

Just strip off the return (13,10) items if you do not need them.

If you do not want to send the return, try sending 'A' (which is the character A, and not the string A.

Update

You can ignore them by:

     if ((incomingByte != 10 && (incomingByte != 13))
     {
        Serial.print("I received: ");
        Serial.println(incomingByte);
     }

If you only want printable characters, check if you can use the isprint function (isprint function

so it should look like

    if (isprint(incomingByte))
    {
        Serial.print("I received: ");
        Serial.println(incomingByte);
    }


How to read 6 RC remote channels using Attachinterupt for every channel How can i use the attach interupt command and read rc channels in background. I am in doubt that attach interupt is only applied to 2 pins just and cant be used to get data from other pins.

I am not sure what you are asking but you can have as many interrupt sources on a single interrupt pin as you want.  When the interrupt happens in your ISR (Interrupt Service Routine) you simply check each one and process the ones that are valid.  Be sure to do one final check before exiting as another could happen while servicing the first one.

Gil


Arduino - read multiline serial input I'm trying to get data from a heat counter via the serial, the format of the response is:

t1=ХХХ.ХХ   t2=ХХХ.ХХ   t3=ХХХ.ХХ   t4=ХХХ.ХХ
P1=ХХ.ХХ    P2=ХХ.ХХ
VolSpd1=ХХ.ХХХ  VolSpd2=ХХ.ХХХ
MassSpd1=ХХ.ХХХ MassSpd2=ХХ.ХХХ
HeatSpd1=Х.ХХХ  HeatSpd2=Х.ХХХ
SumVolume1=Х.ХХХХХХХ    SumVolume2=Х.ХХХХХХХ
SumMass1=Х.ХХХХХХХ  SumMass2=Х.ХХХХХХХ
SumHeat1=Х.ХХХХХХХ  SumHeat2=Х.ХХХХХХХ
PowTime=Х.ХХХХХХХ   PowOffTime=Х.ХХХХХХХ
MeasTime1=Х.ХХХХХХХ MeasTime2=Х.ХХХХХХХ
UnMeasTime1=Х.ХХХХХХХ   UnMeasTime2=Х.ХХХХХХХ

I managed to get the data and parce it on arduino but only from the first line. I do not know how to get all other data.

Since the format is just = , I'd parse it this way, instead of relying on newlines.

Just treat them as whitespace. So buffer all data till an = sign is found, store the buffer as the variable name, then read until you get something other than a digit or decimal point. Then store this as the value. Then do something with the value based on the variable name. Then read and ignore all following whitespace (spaces, tabs, newlines, carriage-returns). And start back from the top.

That way the parse will never get out of whack when some data get missing or something else goes wrong in the serial stream.


How to prevent the Serial Monitor from closing upon re-uploading sketch? I'll be teaching a year 10 class on the Intel Galileo gen2 and there'll be a wide (but high-level) programming curriculum, which includes introduction to console printing, using Serial.

I'd like the students to be able to write their printing code in setup() so that it's only printed once and easily readable by them. However, it's impossible to be fast enough to upload a sketch and open the Serial Monitor (which flat out refuses to open before the sketch has started), and the Serial Monitor closes itself upon re-uploading code.

Without unnecessary (and potentially for the students, confusing) use of the delay function in setup(), it's impossible to read any output originating from setup(); only things printed in loop() (which are constantly re-printed) are ever discoverable.

So; is there a way to somehow keep the Serial Monitor open, or make it capture output from before it's opened, or delay the entire running of the sketch (rather than chucking in delays)?

We'll be using the standard Arduino IDE.

EDIT

This script was run in one of two conditions...

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

  // ensure Serial is ready
  delay(1000);

  for (int i=0; i < 10000; i++) {
    Serial.println(i);
  }
}

void loop() {
}

When the Serial Monitor was opened immediately after upload, all numbers from and including 0 to 9999 were recorded in the monitor.

When the Serial Monitor was opened around 5s after upload, only numbers upward of 2243 were observed. This suggests the sketch WAS being re-run (else no numbers would have been captured; the sketch runs in significantly less time than 5s) but that all numbers between 0 and 2243 were not captured by the monitor; as if opening the Serial Monitor late enough to cause a re-run causes some monitor overhead.
This strange loss of numbers is NOT time dependent: increasing the initial delay from 1s to 4s (and waiting longer after upload before opening the Serial) did not at all vary the soonest number recorded, suggesting it is some 'line' based overhead
(but of course, how could anything fail for 2243 lines?!)

With that mystery aside, this negates the automatic re-running of the sketch upon Serial Monitor opening from being actually useful.

I assume you are uploading the code over USB - the same USB that you want to monitor for output from the sketch? If so, the serial monitor has to release the port for the uploader to be able to use it, and vice-versa, as your computer's OS will only assign a USB port to one application at a time.

It may seem like the IDE is one application containing an uploader and a serial monitor, but the IDE is not much more than a "pretty face" that runs separate compiler and uploader applications on your behalf.

Several work-arounds are possible (although I think a delay() statement in setup() is the clearest of the choices):

Add a delay statement in the setup function. If you must this, you can put it in main() just before the setup() call, but you'd take away a learning opportunity.
Use a separate hardware or software serial channel for the monitor which you could leave connected and wouldn't interfere with uploading;
Use the loop() function instead, and put a forever loop at the bottom to prevent it returning, thus making it a runs-once function.


Controling 5V relay with Wemos D1 R1 I would like to control a 5V relay with Wemos D1 R1 module through webserver. I'm using the following modules:

Tongling 5vdc Relay
Wemos D1 R1

I'm using the following schematic:

and here is the code I'm using:

#include <ESP8266WiFi.h>

const char* ssid = "Myssidname";
const char* password = "Myssidpass";

int ledPin = D3;
WiFiServer server(80);

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

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

 // Connect to WiFi network
 Serial.println();
 Serial.println();
 Serial.print("Connecting to ");
 Serial.println(ssid);

 WiFi.begin(ssid, password);

 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected");

 // Start the server
 server.begin();
 Serial.println("Server started");

 // Print the IP address
 Serial.print("Use this URL : ");
 Serial.print("http://");
 Serial.print(WiFi.localIP());
 Serial.println("/");

}

void loop() {
 // Check if a client has connected
 WiFiClient client = server.available();
 if (!client) {
   return;
 }

 // Wait until the client sends some data
 Serial.println("new client");
 while(!client.available()){
   delay(1);
 }

 // Read the first line of the request
 String request = client.readStringUntil('\r');
 Serial.println(request);
 client.flush();

 // Match the request

 int value = LOW;
 if (request.indexOf("/LED=ON") != -1) {
   digitalWrite(ledPin, HIGH);
   value = HIGH;
 }
 if (request.indexOf("/LED=OFF") != -1){
   digitalWrite(ledPin, LOW);
   value = LOW;
 }

 // Return the response
 client.println("HTTP/1.1 200 OK");
 client.println("Content-Type: text/html");
 client.println(""); //  do not forget this one
 client.println("<!DOCTYPE HTML>");
 client.println("");

 client.print("Led pin is now: ");

 if(value == HIGH) {
   client.print("On");
 } else {
   client.print("Off");
 }
 client.println("

");
 client.println("Click here Turn relay ON
");
 client.println("Click here Turn relay OFF
");
 client.println("");

 delay(1);
 Serial.println("Client disconnected");
 Serial.println("");

}

After uploading the code successfully and watching the monitor, the light gets turned on and I get the following message:
16:02:20.400 -> WiFi connected
16:02:20.425 -> Server started
16:02:20.479 -> Use this URL : http://192.168.100.7/
16:02:41.680 -> new client
16:02:41.680 -> GET / HTTP/1.1
16:02:41.680 -> Client disconnected

However, when I turn on or off the relay using the browser, nothing happens:
19:38:56.010 -> new client
19:38:56.010 -> GET /LED=ON HTTP/1.1
19:38:56.010 -> Client disconnected
19:38:57.016 -> new client
19:38:57.016 -> GET /LED=OFF HTTP/1.1
19:38:57.063 -> Client disconnected

However nothing happens to the light and relay doesn't click.
a few more notes:

I tried in upload the code with relay at high to disconnect the circuit but light is still on
Wemos Network name appears in my network list
It doesn't not respond to AT Commands

The issue lies with Wemos Module where it only outputs 3.3V which insufficient to 5V Relay so this can be solved by implementing 2N2222 Transistor as per schematic below.


Extra "zero" displayed on LCD when integer sent from PC to Arduino through serial port Every time I send an integer from computer to Arduino an extra zero is displayed on the LCD connected to Arduino. I don't know the reason. Why?

Here is the code:

#include <LiquidCrystal.h>

int en = 2, rs = 3, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
int a;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);

void setup() {
    Serial.begin(9600);
    lcd.begin(16,2);

}

void loop() {
    Serial.println("Enter a number");
    while(Serial.available()==0){}
    a=Serial.parseInt();
    lcd.print(a);
}

The result is as follows:

Enter a number
When I enter the number 1
The result 10 is displayed instead of 1

The Serial.parseInt returns zero when it can not find a number within a timeout. That timeout is default one second.
When a number is typed in the serial monitor, often a linefeed is added to it. That linefeed is read by Serial.parseInt. It can not make a number out of that and waits until the timeout and returns zero.

There is no way to tell if the Serial.parseInt returns zero because the number was zero, or if it returns zero because there was a timout.

You can try the next sketch to show the problem. Set the line ending in the serial monitor to linefeed or carriage return or both or nothing and see what happens.

int a;

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

void loop() {
  Serial.println("Enter a number");
  while(Serial.available()==0){}
  a=Serial.parseInt();   // it returns zero with a linefeed !
  Serial.println(a);
}

The easiest way to fix this, is to use a number that is only a single digit. The function isdigit is used to check the incoming characters.

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

  Serial.println("Enter a number (a single digit)");
}

void loop() {
  if (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isdigit(inChar)) {
      int value = inChar - '0';
      Serial.println(value);
    }
  }
}

The Serial.parseInt is not completely useless, but the number zero can not be used. The next sketch ignores the input when Serial.parseInt returns zero.

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

  Serial.println("Enter a integer, but not zero, with a linefeed at the end");
}

void loop() {
  if (Serial.available() > 0) {
    int value = Serial.parseInt();
    if (value != 0) {
      Serial.println(value);
      Serial.println("Enter a integer, but not zero, with a linefeed at the end");
    }
  }
}

To be able to allow to type the number 0, the Serial.parseInt can no longer be used. To avoid waiting and delays, every character is immediately put into a buffer. The sketch becomes larger, but there is no other way. Either use Serial.parseInt or do it right.

#define BUFFER_SIZE 40
char buffer[BUFFER_SIZE];
int index;

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

  Serial.println("Enter a integer, with a linefeed at the end");
}

void loop() {
  if (Serial.available() > 0) {
    bool ready = false;

    int inChar = Serial.read();
    buffer[index] = (char) inChar;
    index++;
    if (index >= BUFFER_SIZE) {
      index = BUFFER_SIZE - 1;
      ready = true;
    }

    if (inChar == '\n' || inChar == '\r') {
      ready = true;
    }

    if (ready) {
      if (isdigit(buffer[0]) || buffer[0] == '-') {
        buffer[BUFFER_SIZE - 1] = '\0';
        int value = atoi(buffer);
        Serial.println(value);
        Serial.println("Enter a integer, with a linefeed at the end");
      }
      index = 0;
    }
  }
}


Infrared frequency recorded with saleae i'm trying to decode infrared signal recorded with the saleae. It makes me wonder why saleae shows so low values for the frequencies from 0.1kHz to 0.8kHz. I found that standard for the IR is around 38kHZ. Is there something wrong with my record? Or did i misread the sample?

What you are looking now is NOT the IR frequency, but the de-modulated signal.

Here is what I'm talking about:

(image taken from http://www.electronicwings.com/sensors-modules/ir-communication)

As you can see, the various pulses are made of smaller pulses.

In your case you are seeing what is here called "Serial data", which is different from the carrier frequency. What the saleae board is telling you is that the width of the high part is 1.625ms, while the width of the low part is 0.631 ms; as you can see, the waveform is NOT periodic, so the "frequency" is meaningless (it's the reverse of the time marked on the view, which is the sum of one large high value and one low value).

Your plot resembles the NEC protocol (see for instance here). A logic '0' is a 562.5µs pulse followed by a 562.5µs space, while the logic '1' is a 562.5µs pulse burst followed by a 1.6875ms space (this is similar to by 0.631 ms and 1.625 ms measurement)


Wait between UART frames I have to reproduce a signal (of 6 UART frames) which have 950 µs delay between each of the frames. Than, a delay of 37ms at the end of those frames.

Everything going right except the delay between each frame...The baud rate is at 9600.

Here is my current code :

  Serial1.write(sw_binary_train_1);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_2);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_3);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_4);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_5);
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_6);
  delay(37);

It's not strange at all.  Serial doesn't block while it sends.  When you call write that pushes the byte into the send buffer and that's all.  Then the code moves on to the next instruction, the delay(950) and during that time the serial data is actually being sent.  It takes about 1 millisecond for that to happen.
This solution works as long as the send buffer doesn't have anything else in it that's slowing you down and as long as you don't change the baud rate.  If either of those things happen then you need to recalculate that time.
A better solution would be:
  Serial1.write(sw_binary_train_1);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_2);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_3);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_4);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_5);
  Serial1.flush();
  delayMicroseconds(950);
  Serial1.write(sw_binary_train_6);
  Serial1.flush();
  delay(37);

The flush blocks until the send buffer is empty again.  That way you don't have to account for that time and all you need the delay for is the time between transmissions.
Even better would be if those things were in an array so you didn't have to keep repeating yourself.  Anytime you catch yourself putting numbers on variable names what you really want is an array so that you can use those numbers in the program:
for (int i=0; i<6; i++){
  Serial1.write(sw_binary_train[i]);
  Serial1.flush();
  delayMicroseconds(950);
}
delay(37)

looks much better.


Trouble reading V_BG I would like to read MUX 14 with the ADC.  On page 263 of the Atmega328 data  sheet it shows 1110b on the MUX corresponding with reading V_BG.

I need to read this so I can calibrate my sensor readings taken with the 5v reference to those taken with the 1.1v reference.  Because the 5v power supply may vary and the 1.1 is more stable, I need to be able to translate the readings taken with a 5v reference based on how the internal 1.1v is read.

Based on the code for analogRead, I wrote this:

int readVBG(int _analogReference) {
  uint8_t low, high;
  ADMUX = (_analogReference << 6) | 14;
  sbi(ADCSRA, ADSC);
  while (bit_is_set(ADCSRA, ADSC));
  low  = ADCL;
  high = ADCH;
  return (high << 8) | low;
}

_analogReference is either 1 or 3 depending on the reference voltage desired.

I expect to read 1023 when _analogReference is 3 and about 225 when _analogReference is 1.  Instead I get smaller values which I'm guessing are from a floating (unconnected) analog pin.

The problem is that a 2ms delay is required after setting the ADMUX bits before starting the conversion.  Thank you Majenko for the link.

int readVBG(int _analogReference) {
  uint8_t low, high;
  ADMUX = (_analogReference << 6) | 14;
  delay(2); // Wait for voltage to settle
  sbi(ADCSRA, ADSC);
  while (bit_is_set(ADCSRA, ADSC));
  low  = ADCL;
  high = ADCH;
  return (high << 8) | low;
}

The above code is specifically for the Arduino UNO.  Majenko's link above has #ifdef statements which support other devices.


Error using nRF24L01+ with ATmega328P-PU. Works fine on Uno I am trying to use a nRF24L01+PA with an ATmega328P minimal breadboard system. I first connected the module to my Uno and verified it with the "scanner" example sketch from the rf24 library, which showed:

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

It also shows the readings from each channel after; I just omitted that part.

Removing the chip and reconnecting it to my breadboard ATmega, which has been bootloaded and tested with the blink sketch, I get the following:

STATUS       = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1     = 0x0000000000 0x0000000000
RX_ADDR_P2-5     = 0x00 0x00 0x42 0x42
TX_ADDR      = 0x1042082184
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x00
EN_RXADDR    = 0x00
RF_CH        = 0x00
RF_SETUP     = 0x00
CONFIG       = 0x00
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = Disabled
PA Power     = PA_MIN

I double-checked all my wires against an ATmega328P pin map and everything checks out.

Furthermore, running the "gettingstarted" sketch on my Uno returns the correct result in the serial monitor where the chip starts in receiving mode and waits for instructions or to receive packets. And because I don't have the other chip set up yet, nothing shows up. However, when I run the exact same program on my breadboard ATmega, I get the following right after it finishes uploading.

RF24/examples/GettingStarted
*** PRESS 'T' to begin transmitting to the other node
Sent response 4194829060
Sent response 4194829060
Sent response 4194829060
Sent response 4294967295
Sent response 4294967295
Sent response 4294967295
Sent response 0
Sent response 4294967295
... yada yada yada

The fact that it is picking up any signals doesn't make sense as I am not transmitting from anything... yet.

The only MAJOR difference between my breadboard setup and the uno is the uno is running off USB 5V and the antenna is getting power from the 3.3V pin. On my breadboard, I have my usb2serial jumpered to 3.3V right off the bat and it is running the ATmega328P with a 16MHz crystal basically at 3.3V (waiting on my 3.3V regulators to arrive this Friday so I can run the chip at 5 and drop down to 3.3 just for the chip, as it is a potential solution I have in mind but in the meantime I am asking for other possibilities). Yes I know it is low but so far other sketches like the blink work, and I am running the chip in receive mode anyways.

I am lost and would appreciate some guidance.

Thank you.

The ATmega328P can't run at 16MHz at a supply voltage of only 3.3V (check the datasheet). Either raise the voltage or lower the frequency.

Also note that 16mHz would be 16 milliherz (16E-3), so you probably mean 16MHz, i.e. 16 megahertz (16E6).

Remember that the nRF24L01+ is a 3.3V device, so don't connect it to the ATmega's Vcc when changing the supply voltage to 5V.
The IO pins are 5V tolerant, so that's not an issue.


PCF8563 does not remember time when restarting Arduino Uno? I'm trying to use the following RTC module (PCF8563) with Arduino Uno.

I am using this library to set/get time and date from PCF8563. However, whenever I shut down the Arduino, the time/date is lost! Even though, as you can see in the picture, the module is equipped with a 3V battery to keep running when Arduino is unplugged.

Any help would be highly appreciated!

[SOLVED]

The solution is simply to put a jumper between BAT and VCC positions in the module itself. Many thanks to Edgar Bonet


Is supplying 5V from both external 5V and USB harmful? I have an arduino nano which is powered through unregulated 5V (pin 27). For debugging purpose, I'd like to connect the USB port to my computer in order to use the Serial.Print function. The external 5V will stay connected. Will this cause damage ?

edit : I forgot to mention that the external power supplied to pin 27 is regulated with a switching DC-DC converter (measured 5.1V). Sorry it was not clear in my question.

Here is my circuit :

The switching regulator is not exactly the one in the schema.

Is using the circuit with the battery power supply + usb connection to my computer will damage something ?

No, it probably won't damage anything, as the PC's USB port is protected from overvoltage by the D1 schottky device on your arduino board.

Update, my previous answer contained the following paragraph, which is not related to your problem

  But you should take care of some things.

  Make sure, the voltage applied to your +5V-Net is regulated properly elsewhere. I.e. choose a laboratory PSU or another good
  source.
  Avoid having both your PC and your 5V-supply connected to line voltage. Ground levels may differ due to Y-capacitors present in the
  switching PSUs. Those provide a AC voltage of half your line voltage
  to DC ground (only with 0.3 to 0.7 mA, but enough to cause
  disturbances on your signals at 55 volts in the US or 115 V in the EU)
  If you have to use two switching PSU for both PC and arduino, provide an equipotential bonding between your PC's mass (e.g.
  VGA-port-screw) to your arduino's PSU's ground directly, to prevent
  leakage currents from the Y-capacitors wandering around in your
  circuitry.

Update according to your enhanced question

You are using a battery powered DC-DC supply for your Arduino. So, my previous notes do not apply to your problem.

5.1 V seem exact enough to drive your arduino safely. No need for additional stabilisation measures
D1 (see genuine arduino schematic) separates USB-Power from +5V and prevents current flowing in reverse direction over your USB connection.
Arduino circuitry and USB port have common GND so there are always well defined voltage levels.

In my opinion, there's nothing with your setup, which may harm your circuitry or your PC.

Depending on the maximum power of your DC-DC converter you may consider adding a fuse to protect converter and components in case of short circuit.


Need help understanding how RF communication works with 2 arduinos I have two arduinos (uno) and I would like to send the results of a key press on a 5X4 matrix pad to the other arduino. The matrix keypad works great. I can identify which key was pressed with a switch function.

switch (keypad())
//switch used to specify which button
     {
      case 0:
        Serial.print("Key A Pressed");
        Serial.print(keypad());
        messageToSend = 0;
      break;
        case 1:
        Serial.print("Key B Pressed");
        Serial.print(keypad());
        messageToSend = 1;
      break;
        case 2:
        Serial.print("Key C Pressed");
        Serial.print(keypad());
        messageToSend = 2;
      break;
       }

My RF units are both nrf24l01. I have tried working with the sample code and I think the issue is I don't understand how the unit works well enough.

What is the nature of the data sent between units? I want to send
integers, possibly even text. Is that possible? Do I need to convert
to binary or something?
My understanding of "ping" and "pong" is that ping sends a message
then pong sends that same message back to ping... is this correct?
Are RF units very different? Is this one particularly difficult?
If I just want to send with one receive with the other shouldn't
this simplify the code?
What are pipes? How many can I open?
If I have 3 or more of these what changes will I need to make to the
code?

Thanks!

Many questions so broad answers, but hopefully informative for your research

  What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?

It depends broadly on what you use. If you use an ethernet peripheral then the communications will be entire ethernet packets with whatever protocol stack you have above it in payload. For simple RF communication modules it may be as simple as a serial stream delivered 8 bits at a time. The simplest rf (buzzer-style) would simply interrupt (or drive a pin high) when the transmitter is sending a signal.

In Your case the transmitter uses an addressed protocol with a payload packet of between 1 and 25 Bytes of data. This means that you will need code to read and store the necessary payload, maintain configuration data and keep track of addresses of the other systems to message. You also need to poll (or handle interrupts from) the rf module to make sure there aren't messages from the transmit node.

How you convert the data is up to you, a string can be represented by a sequence of bytes and can be send and read as a string on the receivers end. Your rf module will deliver you data in 1-25 byte chunks, what you send in that chunk and how to encode it is entirely up to you.

On the low level,the way this module is configured, the MCU sends data into the rf ic using a serial protocol, the module incorporates a buffer to allow the MCU (slow - 8 bit) to send the data and not have to keep up with the 1Mbps throughput of the rf. On a physical level the signals of the chip look thus:

  My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?

Ping Pong is a game and not a well defined technical term. For precision you can define ping-pong as an echo where the transmitter effectively acknowledges the message by re-transmitting it back to you.

  Are RF units very different? Is this one particularly difficult?

RF units can be very different depending on what high level protocol they offer. This unit is somewhere half way between full blown wifi and simple and modulated RF communications. It gives you addressing and error correction as well as a robust communication scheme

This particular unit is made to be relatively "modern", it uses GFSK - a frequency modulation scheme -to transmit and receive data to uniquely addressable nodes on a number of channels. At 2.4 GHz it is high throughput, legal.  It is not the simplest toy.

In terms of simplicity, this module has a lot of examples and documentation, given that it has an arduino library it has a high likelihood of working and succeeding, but you will need to use more advanced microcontroller features to fully utilize the device (e.g. interrupts, DMA).

For other RF options there are lots of things to consider. Going up to wifi requires you to maintain a much more complex stack, meaning more processing power and code, if you want to offer TCP/IP services (say webserver) it is even more code but can be done on an 8 bit arduino. Going down to simpler protocol may win you less power and simpler code but a headache to expand.

  If I just want to send with one receive with the other shouldn't this simplify the code?

You will still need to implement both a receiving and a transmitting application so the work is still all there, it will simplify the higher level logic into separate application which is easier.

  What are pipes? How many can I open?

I see nothing about pipes from a cursory glance at the docs, perhaps you can illuminate more on what you are confused about?

In general pipes are a "hole" where an application (in the broadest sense) can stream data and it will be consumed by whoever is on the other end, a black hole of a serial data stream. You can implement a pipe as a high level software construct that will buffer and consume data from peripherals and wait to send it out the RF transmitter, it may also be implemented on a hardware level with discrete buffers and additional logic around the rf transmitter etc. As a conceptual element you can probably use a "pipe" concept for communication between the different devices in your code (e.g. move byte to pipe 1 for device 1, move byte to pipe 2 for device 2, let the "driver" handle order), this is a design paradigm that makes software development easier.

  If I have 3 or more of these what changes will I need to make to the code?

The rf module is fully capable of addressing up to 65,536 unique hosts, so the device is fully ready to talk to 3 of your hosts, however the software logic needs to track the addresses and other comms data about each host as well as process the data for them (if its different) in enough time.

If you are expecting this in advance, good design decisions early on (e.g. small API or library) will make this much easier on yourself to add features in the future.

Final Thought

If you need a simple echo, this may be a bit overkill for your system, however it is relatively powerful and may make it easier for you to program since you can work with "real-world" data units and send multiple byte packets easily.

I would highly recommend you read and understand the datasheet for the RF chip, be thankful that the nice library takes care of the messy details for you, but understanding how it works will certainly help you understand how to use it best.

An 8 bit Atmega may not be powerful enough to process and transmit 3 separate streams together (if they are identical its less difficult) if you require a constant high rate transmission or if you do a significant amount of processing on the arduino before sending you will feel the limitations of the chip and a 32 bit board may be worth looking at.


Store & retrieve parameters after sketch update I have a Generic code for some IOT devices which vary in some parameters ( lets say it is only its MQTT name and subscriptions).
Since I use OTA to update sketch, I'm looking for a way to A) write those parameters into the ESP32/ ESP8266 FS, and B) They will survive an update.
My only solution come into mind is using an SD card which does not get erased after OTA, and I'm looking for a way doing it not involving SD or external memory.
Guy

There is no need for an SD card.
You can write all relevant parameters into a file in SPIFFS (e.g. json if you like) before starting the OTA update. During initialization you read the file and set the parameters accordingly.
SPIFFS does not get erased when doing an update (at least that's true for the OTA library that I'm using). If it does get erased in your case, there probably is an option in the OTA lib to disable flash erase, just like there is the same option when uploading a sketch via serial.


Servomotor AND Button I am having trouble trying to make servomotor and button work together. The button code here below works fine when alone in a separate code but when it is transferred to the code with the servomotor function in it, it doesn't work.

Is there anything I need to be wary of when integrating the button code here to the preexisting code?

#include <Servo.h> // Library required for the servomotor (Make sure to download)
#include <Button.h> // Library required for the microswitch (Make sure to download)

// Parameters for the experiment
// Note: 1000 is one second
char Experiment = 'Acclimatization';
char Bird_Name = 'birdname here';
int Frequency = 30 * 1000; // The motor moves every x seconds
int Frequency_Deviation = 5 * 1000; // There are x second deviations plus and minus from the frequency set above
int Duration = 3 * 1000;  // The food is uncovered for x seconds

int servoPin = 9; // Declare the servomotor pin (Can be varied from setup to setup)
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)

Servo Servo1;

void setup() {
   Servo1.attach(servoPin);
   //analogWrite(servoPin, 0);
   Serial.begin(9600);
   button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop(){
   // Get onset and offset times of when the bird arrives and leaves the perch
   button.loop();
   if(button.isPressed())
    Serial.println("OnsetTime");
   if(button.isReleased())
    Serial.println("OffsetTime");

   // Calculate the acclimatization parameters below
   delay(random(Frequency-Frequency_Deviation,Frequency+Frequency_Deviation)); // Calculates frequency (See paramaters above)
   Servo1.write(0); // Starts from 0 degrees
   delay(Duration); // Duration that the food is uncovered (See parameters above)
   Servo1.write(75); // Goes to the x degrees
}

Short answer: You have a blocking delay interrupting your button debounce time of 100ms.

Your button library has a debounce time of 100ms. This means you must be holding the button down for more that 100ms before it will register as pressed.

You have a 3 second blocking delay at the end of your loop. When you call delay(XX), your processor cannot do anything during this time (like check for a button), it's just waiting.

Think about how the code is running. In your main loop, you are calling the function button.loop(), and it's checking to see if your button is pressed. If it's pressed, it's starts a timer (your debounce). The goal of this timer is for another 100ms to pass by with your button still being pressed to make sure you actually pressed it. Button.isPressed() fails, and it moves to its next set of instructions, which is move the servo and wait 3 seconds, during which time it cannot check the button. Then it starts all over again, and it calls button.loop() again. This all happens MUCH faster than 100ms. From the start of void loop() to the time it takes for it to wind back up at the 3 second blocking delay is in the nano seconds. This never gives your button library the 100ms of "pressed down" button it needs for button.isPressed() to return true.

I suggest spending some time looking at the behind the scenes of your button library and see how the debounce works. You can do that, or you can use the example debounce sketch off the main arduino website and learn how that works. The next thing you'd want to do is to learn how to make your code "wait" without using the blocking call delay(). This is done by using timers with millis(). A good way to learn this is the example arduino sketch "Blink Without Delay".

Hope that clears some things up.


How can I move an arduino library into my project repo and use it from there? I've got this project that that is using the LiquidCrystal.h library. My import looks like this...

#import <LiquidCrystal.h>

I've tried making a 'libraries' folder in my repo, and copying the LiquidCrystal directory from arduino's global libraries folder to my_project/libraries and changing my import to...

#import "libraries/LiquidCrystal/LiquidCrystal.h"

and it explodes on me. I know the path is right, because it gives me a different error if I change the import path to be wrong... but even when it's right, I get this traceback...

Arduino: 1.8.1 (Mac OS X), TD: 1.36, Board: "Arduino/Genuino Uno"

/var/folders/sz/cdsmvqws6rq9839mhd802prm0000gp/T//cc4gIISN.ltrans0.ltrans.o: In function `__static_initialization_and_destruction_0':
/Users/chris/art/greenhouse/greenhouse/greenhouse.ino:36: undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
etc....

What's the deal? Aren't I supposed to be able to import libraries with an absolute path to the library? This is literally the same file.

What is the difference between #import <foo.h> and #import "my_libraries/myfoo.h" ?

What's the deal? Aren't I supposed to be able to import libraries with
  an absolute path to the library? This is literally the same file.

Yes you can use both absolute and relative paths, but "libraries/LiquidCrystal/LiquidCrystal.h" is a relative path because it doesn't start from C:\\ or / basically. Also make sure you get the LiquidCrystal.cpp file which actually contains all the functions LiquidCrystal.h specifies.

  What is the difference between #import  and #import
  "my_libraries/myfoo.h" ?

#include "my_libraries/myfoo.h" specifies that myfoo.h is in a folder my_libraries first searched for in current_folder/my_libraries/myfoo.h then quote directories and rest of the search paths later, #include <foo.h> specifies that foo.h is a system header, it's only searched for in search paths.

Solution here would be saying inside your sketch that it is in a subfolder, that the folder is one folder below and then two folders deeper for ex. #include "../libraries/LiquidCrystal/LiquidCrystal.h" this here assumes your sketch is in root_folder/Sketch/Sketch.ino and library in root_folder/libraries/LiquidCrystal/LiquidCrystal.h.


How to webClient.write() an image stored on a String? My application runs on an ESP32-CAM.
It takes pictures and stores to SPIFFS.
Periodically SPIFFS is checked and if images are found:
1- The image is saved to a FTP server
2- The image is summited to a Web Service that returns some informations about the image
3- Values are saved to mySQL
4- The image is deleted from SPIFFS
To read the image from SPIFFS I use the following fragment of code:
String imageName   = file.name();
imageBuffer = "";
while (file.available()){
   imageBuffer += char(file.read());
}

The FTP transfer works perfectly with the following command:
ftp.WriteData((uint8_t*)imageBuffer.c_str(),imageBuffer.length());

The service the image is submited for analizes works OK if I use the command:
webClient.write(fb->buf,fb->len);

But as it is not usable in the current implementation of my project I am trying to work with:
webClient.write((uint8_t*) imageBuffer.c_str(), imageBuffer.length());

I get no errors in return but it just does not work and the web service at the destination returns nothing.
What Am I doing wrong?

You should not use String to store binary data.
Instead allocate yourself an array of uint8_t of the right size.
uint8_t *imageData;
size_t len = file.size();

imageData = alloca(len);
file.readBytes(imageData, len);

webClient.write(imageData, len);

With that said, without knowing what the rest of your program is doing I can only surmise that you're just blasting raw data at the web server and hoping it sticks. That's not how web data transfers work. You have to craft the upload page properly as multi-part mime form data. Read this for more information


Arduino bug when "myFile = SD.open" is inside loop() My Arduino resets / bugs each time I put myFile = SD.open in loop().

In setup() it works fine.

I have a 20*4 LCD and an RTC connected to I2C, an SD card reader connected to SPI, and a fingerprint sensor.

Here is my code:

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <SD.h>
#include <DS3231.h>;

LiquidCrystal_I2C lcd(0x3f,20,4);
DS3231  rtc(SDA, SCL);
SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
Sd2Card card;
SdVolume volume;
SdFile root;

int etat = 0;
int getFingerprintIDez();
const int chipSelect = 10;
SDFile myFile;

void setup() {
  lcd.init();
  lcd.backlight();
  rtc.begin();
  finger.begin(57600);
  SD.begin();

  // Reglage Heure
  //rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY
  //rtc.setTime(10, 57, 0); // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(24, 11, 2016);   // Set the date to January 1st, 2014
  if (finger.verifyPassword()) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Initialise");
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Capteur Deconnecte");
  }
  delay(2000);
  if (SD.exists("data.csv")) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("data.csv OK.");
    delay (1000);
  } else {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Creating data.csv...");
    myFile = SD.open("data.csv", FILE_WRITE);
    myFile.close();
    delay (1000);
  }
}

void loop() {
  if (etat == 0) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Put Finger");
    getFingerprintIDez();
  }
  if  (etat == 1) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("ID #");
    lcd.setCursor(4,0);
    lcd.print(finger.fingerID);
//  myFile = SD.open("data.csv", FILE_WRITE);
//  myFile.print(rtc.getDateStr(1));
//  myFile.print("\t");
//  myFile.print(rtc.getTimeStr(1));
//  myFile.print("\t");
//  myFile.println(finger.fingerID);
//  myFile.close();
    lcd.setCursor(0,2);
    lcd.print("Loged");
    etat = 0;
  }
  delay(1000);
}

int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Found ID #");
  lcd.setCursor(14,0);
  lcd.print(finger.fingerID);
  etat = 1;
  return finger.fingerID;
  delay(1000);
}

Each time I uncomment lines using SD, the Arduino resets at the end of the loop.

What is the problem?

The solution to your problem is to extend your 2 states machine in a multiple states machine.

Declare the enum eState before setup():

typedef enum e_State {
    STATE_START = 0,    // starting the loop (add some initialisation)
    STATE_READ_FINGER,  // Step1: read the finger print
    STATE_DISP_FINGER,  // Step2: display the finger print
    STATE_OPEN_LOGGER,  // Step3: open the log file
    STATE_WRITE_LINE,   // Step4: append a timestamp finger print
    STATE_CLOSE_LOGGER  // Step5: close the log file
} eState;

And update the loop() function with the state-machine:

void loop()
{
    static eState LoopState = STATE_START; // to store the current state

    eState NextState;  // for the next loop

    switch (LoopState) {
    case STATE_START:
        // add additional settings
        NextState = STATE_READ_FINGER;
        break;
    case STATE_READ_FINGER:
        etat = 0; // keep use your 'etat'
        // or return a boolean from your 'getFingerprintIDez()'
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Put Finger");
        getFingerprintIDez();
        if (etat == 1) {
            NextState = STATE_DISP_FINGER;
        }
        break;
    case STATE_DISP_FINGER:
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("ID #");
        lcd.setCursor(4,0);
        lcd.print(finger.fingerID);
        NextState = STATE_OPEN_LOGGER;
        break;
    case STATE_OPEN_LOGGER:
        myFile = SD.open("data.csv", FILE_WRITE);
        if (myFile) {
            // record only if file is opened
            NextState = STATE_WRITE_LINE;
        }
        else {
            lcd.setCursor(0,0);
            lcd.print("Can't open file");
        }
        break;
    case STATE_WRITE_LINE:
        myFile.print(rtc.getDateStr(1));
        myFile.print("\t");
        myFile.print(rtc.getTimeStr(1));
        myFile.print("\t");
        myFile.println(finger.fingerID);
        myFile.flush();
        NextState = STATE_CLOSE_LOGGER;
        break;
    case STATE_CLOSE_LOGGER:
        myFile.close();
        lcd.setCursor(0,2);
        lcd.print("Loged");
        NextState = STATE_READ_FINGER;
        etat = 0;
        break;
    default:
        NextState = STATE_START;
    }
    // next loop()
    LoopState = NextState;
    delay(200);
}


Best practices for really long distance sensor deployments I'm noob to Arduino and electronics, but here is a problem from life which I need to solve for myself:

We grow strawberries and early spring freezes can take most of the flowers from the plants. One way to protect this is to have some kind of heating in solar houses, but if you grow outside, your best option is to watering the flowers on the crops when the freezing comes.

I want to deploy at least 3-4 temperature sensors, which are placed at every parts of the land, which will send the data for an Arduino which will turn on the pump with a relay (for this part I also want to use a pre-built relay solution with socket plugs already built, I don't want to mess around with high electricity myself).

For a cable solution (like catKIT system) I need at least 100m cable for the farest part of the land, which can be managable, but later on, scaling the land lots of cables everywhere can be a problem.

So the best solution would be if every temperature sensor is a standalone station, data transmitted by wireless to the main Arduino which is triggering the pump. This way there will be lass cables on the land, less change to cable break by tractor, etc.

Also, with a wireless system, I don't have to deal with signal loss over the cable, just only wireless signal loss. Is it possible to correct this by middle wireless signal transmitter stations? Or even better, all of them connected to each other!?

Like if the farest sensor reading Celsius 0.8, middle sensor reading Celsius 1.2. Middle sensor have a variable to also consider any reading from the farest sensor, which is reading 0.8. If that reading under Celsius 1, than don't bother his own output, send 0.8 to the main Arduino which is triggering the pump.

These station's power input still need to be solved, but maybe solar panels can be an option? However I have a clue that night they will not work, most of them freezing comes at night.

I saw wireless shields for arduino which offering even a km range in ideal conditions. But how degrading when the conditions are not ideal, like a house wall, rain, fog, snow?

Is it possible to feed multiple wireless inputs too one arduino? 3-4-10-20 standalone stations which transmitting temperature reads for the main arduino. If one of them sends lower temperature than +1 Celsius, than the pump will be turned on. Is it possible to solve this?

Thank You for your answers!

There's as many ways of solving your problem as there are of skinning a cat (those poor poor cats - always getting skinned... ;) )

As you have already noted there are two basic solutions: wired or wireless.

Wired does have one major advantage that you haven't really touched on (only mentioned in passing) and that is power. With a wired solution you can provide power over those same wires so you don't need to worry about solar panels, batteries, whatever. But wires can break, yes. So they're not ideal. But then what is?

With wireless you then introduce the major problem of power. Solar panels are one possible way of getting power, though they are expensive, and you need to "over spec" them to charge batteries so you continue to have enough power for the times when is little or no sun.  Complementing them with wind power is also an option to boost the battery charge when its windy. It all adds up to very expensive sensors though.

A compromise might be to consider both options together.  Turn the sensors into small clusters of sensors that are near by with a base station for those sensors that both gathers and stores the power needed for them, and performs the wireless communication. The sensors would then be wired to the base station.  Your wires are then shorter, and your power is more centralised.

But what to then use for the wireless itself? Well, there it's really all down to frequency.  There's two basic gropings here:

High frequency - 2.4GHz - is great at unobstructed communication. That's the frequency your WiFi works on, and as you probably know it's great if there's no walls in the way. Add walls and the signal drops off considerably.
Low frequency - 433MHz - Far far better at penetrating walls and things but much less bandwidth.

I have had distances of hundreds of meters using a 2.4GHz nRF24L01+ module with power amplifier and antenna. That's in open air with (pretty much) line of sight. Indoors the range is much much shorter. Put buildings in the way and your hundreds of meters drop down to tens of meters.

So if there are obstructions you're pretty much going to want to use the 433MHz range (there is another frequency, which is different depending on where in the world you are - 868MHz or 915MHz, so we'll ignore that for now).

There's plenty of modules around that run at 433MHz, some better than others. There is, however, a new standard emerging now that is designed specifically for this kind of thing - long range, low bandwidth, just for sensors (as part of the IoT bandwagon) called LoRa (short for Long Range) which aims at distances of 15km using very small amounts of power (tens of mA) which is ideal for solar powered operation. It also can use the 868/915MHz region as well.

The final option that you touched on without knowing it is that of a mesh. This is where all the nodes form a network and each node is capable of relaying data from other nodes to get to their destination. Kind of like how the internet works. There are some mesh libraries available for some radio modules on the Arduino, but I have no idea how good or reliable they are. The best ones would be completely self-healing with auto-discovery - add a node and the whole mesh works out how to route messages to the destination node; remove a node and the mesh works out new routes to pass the data around the hole it's created.

Creating a good mesh stack is not child's play, so you would want to research it properly and find the best modules with the best library support if you wanted to take this route. That's why LoRa is taking off - it's so much simpler to get wide coverage without the need of complex mesh systems.


Digit LED has single input, multiple outputs for each segment. Concerns about "sinking" 5v supply into digital pins The model name is 5161BS

Pins 3/8 are input and the rest are output for each individual segment.

I have connected pin 3 to the 5v pin on the Arduino, and the rest to individual digital pins.

With a simple sketch with the pins set to mode output, all segments are lit.

My concern is that the way I am turning off each segment is by setting the output pin to high.

Meaning

5v pin --> LED <-- Digital pin

Is this dangerous to have two voltage sources going in the same direction? Is there another way to do this?

The device you have is a common anode display. This means that the anodes (+ve terminals) of all the LEDs are connected to one common pin (well, 2 pins actually, pin 3 and 8 are connected internally) . Their cathodes (-ve terminals) are what make up the remaining pins. Now, to light up any LED, you need 5 V at its anode and GND at its cathode. You have connected 5 V to pin 3, which stands for the common anode of every LED, so all that is left for any LED to turn on, is for you to connect GND to its corresponding cathode. So when you made all the remaining pins (the cathodes) OUTPUT, by default the Nano sets those pins to a logic LOW (or GND) value, so ALL the LEDs got lit up. Each LED now has 5 - 0 = 5 V across its terminals and is forward-biased.

However, when you write HIGH to any cathode, the potential difference across the associated LED/segment is now zero, because that LED has 5 V at its anode (pin 3/8) and 5 V at its cathode (as a result of writing HIGH), and 5 - 5 = 0 V so it is reverse-biased (at least 2 V or thereabouts is needed for a red LED to become forward-biased) and so the segment turns off. And this is how you control which segment is on at any time: You write a LOW to a cathode to turn on the associated segment, and write HIGH to turn it off. It sounds counter-intuitive but it follows if you think about it. Regarding your question, there's no damage being done to anything; the minimum voltage across the LED is 0 V (well below its maximum peak inverse voltage), while the maximum voltage across the LED is around 2 V, if you use the highly recommended current-limiting resistors (220/330 ohms is good) in series between each cathode and its Arduino digital pin.

Without any resistors, you will be drawing a lot of current through each pin, in total, a lot more than the Nano can safely supply. Use resistors that limit the current through each LED to 10-20mA.


Using timers on an Arduino Mega 2560 I'm an amateur and I wish to use timers in my project. I'm using an Arduino Mega 2560 with a touch-sensitive screen with six  DS18B20 temperature sensors and a DS1307 RTC (real time clock). I would like to query my sensors every 1 or 2 minutes to refresh the screen for temperature acquisition. I do not how to program timers to schedule the readings and which timers to use?

You can use the function millis(), that returns the number of milliseconds since the Arduino board began running the current program (unsigned long). This number will overflow (go back to zero), after approximately 50 days.

The code below uses the millis() function, a command that returns the number of milliseconds since the Arduino board started running its current program, to blink an LED.

/* Blink without Delay

 Turns on and off a light emitting diode(LED) connected to a digital
 pin, without using the delay() function.  This means that other code
 can run at the same time without being interrupted by the LED code.

 The circuit:
 * LED attached from pin 13 to ground.
 * Note: on most Arduinos, there is already an LED on the board
 that's attached to pin 13, so no hardware is needed for this example.

 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

// constants won't change. Used here to
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Source: http://arduino.cc/en/Tutorial/BlinkWithoutDelay


Is I2C a good option for transmitting data over 200 meters by cable? Is I2C a good option for such application or are there other protocols? I know that modules like these exists to extend I2C range, and I'm planning to use this one (P82B96).

I'd like to use a frequency of 100kHz for I2C and use DMX cables of 20m connected in series.

So, is there any alternative that is more adapted for Arduino to Arduino data transmission over a cable?

EDIT : The solution here is CAN because it allows to have multiple devices on the bus. But if it is a simple communication between two arduinos, then go for the RS-232.
Solution mentionned by @Dmitry Grigoryev and @Joe S

Thanks in advance.

With I2C, you're unlikely to get reliable communication on a cable longer than 1m. For your reference, here's a table showing what you can achieve with regular RS-232:

Length (m)  Maximum Baud Rate
1600        600
800         1200
400         2400
200         4800
100         9600
50          19,200
25          38,400
16          57,600
8           115,200

So, if you don't really need 100 kHz data rate, you could use regular RS-232 (which is cheap). If RS-232 is not fast enough for you, consider more complex solutions. RS-485 is one possiblility. Another one is CAN, which supports topologies up to 500m at 100kHz. The key difference of CAN is that it's a bus, meaning that all devices will share the same pair of wires.


Can I use the Arduino Uno's 3.3v pin while powered by a 9 volt battery? I have an Arduino Uno. It has a 3.3v pin that I would like to use to power another module that requires 3.3v, and nothing more. If I power my Arduino Uno with a 9 volt battery, will this pin output 3.3v, or will it give more than that?

The 3.3v is regulated and will always output 3.3v if the device is powered on.


Why my Galileo isn't getting a IP address? I have an Ethernet cable connected to my router. I connected the other end to my laptop and got a successful connection. When I plug it into my Arduino Galileo gen2, even with Ethernet port green light on, I got nothing when I run this:

delay(1000);
system("ifconfig eth0 > /dev/ttyGS0");

This is my output:

eth0      Link encap:Ethernet  HWaddr 00:00:00:00:00:00
      BROADCAST MULTICAST  MTU:1500  Metric:1
      RX packets:0 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
      Interrupt:41 Base address:0x8000

What I'm doing wrong?

I really don't know why, but after I initialized the Ethernet interfaceifconfig eth0 up it started working properly. I don't know why this time this command was needed and the others didn't.


Connecting two sensors with bluetooth I am new with Arduino. Im working in a school project, and I decided to create a glove with shock sensor for goalkeepers and need a ultrasonic sensor next to the ball, so i can know when the ball was kicked.

I need the data from both sensor.

Is this possible with only 1 arduino?, where the arduino is with the ultrasonic sensor and the shock sensor is connected with a bluetooth module to send it to the arduino.

Or, I have to use 2 arduinos?, one with with the glove and the other with the ultrasonic sensor and connect both with bluetooth?

If this is not the best way, can you help me with some ideas to do it? Thank you.

This to be possible with only 1 Arduino depends in your sensor. It is most likely not possibpe without another microcontroller (not nesessarily an Arduino) because of the following reason.

Most bluetooth modules on the market (linke the HC-05 vor HC-06) are bluetooth serial modules, meaning that they build a serial connection over bluetooth and provide the corresponding two pins (RX and TX). Yet most sensors don't implement an UART interface (the Serial interface in Arduino), but only give an analog or digital output voltage. With much work you might be able to tweak the firmware of the bluetooth chip for reading and sending a digital value, but this would be more work, than the price of a second microcontroller would justify.

So I would try to add a small microcontroller (like an ATTiny85) to the sensors side. It can measure the sensors output voltage and then send it via Serial to the bluetooth module. You might also want to use another Arduino here, though this might be an overkill. Maybe a really small version.

After some thinking I had the idea, that it might be possible to send an analog voltage from the sensor through a audio bluetooth module without using another Arduino. Though I'm not sure if this really would work and which module you need for that.

All in all I still would go for the extra microcontroller and serial interface bluetooth, because it is much easier for a beginner.

EDIT:

Above I mentioned using Serial on an ATTiny85, which is not directly possible, since it does not have a full UART hardware (but only a USI). Though you can use the standard SoftwareSerial library on it. If the rest of your code isn't to big, it should still fit in the small memory of the Tiny.


Trouble with ESP8266 on Eero network I have an ESP8266 Node MCU and am learning to use its wifi capabilities. In my home I have a router provided by my ISP that runs a network we'll call 'network1'. I also have an Eero mesh network that runs in the house, called 'network2'.
When I upload the following minimal example and use network1,

my 8266 device connects to network1 (the messages in the serial monitor confirm this) and
I can use my phone and laptop to connect to the 8266 - i.e., I can put the IP into my browser and see a webpage telling me 'Hello World'.

However, I have trouble with network2, the Eero network.

I can connect my 8266 device to network2 (the messages in the serial monitor confirm this)
but
I can't connect to the 8266 device with my phone/laptop. (Yes, I switch these over to network2 first.) I put the new IP into my browser and I am told the page is taking too long to respond.

I haven't done anything special with my network1 router; things just worked. With network2, I've tried various settings with my Eero - given the 8266 a static IP address, enabled port forwarding (on port 80) and established a firewall rule for it, but nothing works.
I can run many different programs through network1, and nothing works on the Eero network. Any suggestions on getting things to work?
My minimal working example:
#include <ESP8266WiFi.h>

const char* ssid = "network1"; // or 'network2'
const char* password = "thepassword"; // real password used in code

WiFiServer server(80); //just pick any port number you like

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

  // Connect to WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
  //gateway = WiFi.gatewayIP();
  Serial.print("GATEWAY: ");
  Serial.println(WiFi.gatewayIP());

  // print your subnet mask:
  //subnet = WiFi.subnetMask();
  Serial.print("NETMASK: ");
  Serial.println(WiFi.subnetMask());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\n";
  s += "Content-Type: text/html\r\n\r\n";
  s += "<!DOCTYPE HTML>\r\n\r\n";
  s += "\r\n";
  s+= "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n";
  s+= "<title>ESP Web Server</title>\r\n";
  s+= "\r\n";
  s += "Hello World";
  s += "\n";

  client.flush();

  // Send the response to the client
  client.print(s);
  delay(1);
}

I was able to find an answer though I'm not sure why it works. It comes down to adding WiFi.mode(WIFI_STA); in the setup, as in
void setup() {

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  ...
  }

I was able to replicate success with another file on my ESP8266 device and Eero network as well.


Debugging RN 42 HID Mouse I'm trying to use the RN 42 and Arduino Uno to control a bluetooth mouse. I configured the RN 42 with the commands S~,6 and SH,0220 and R,1 to put the device in HID mouse mode. Is there anything I missed? Below is the sketch I am using to send mouse reports to the bluetooth. The sketch compiles fine, but moving the joystick does not move the cursor. I included a line of code at the end to print on the serial port whatever data is being sent through software serial to the bluetooth. However when I view the serial monitor, I get back a lot of reversed question marks. Anyone know why this is? Thanks in advance.

const int bluetoothTx = 4;    // TX pin of RN-42, Arduino D2 (configure as RX pin of Ard)
const int bluetoothRx = 3;    // RX pin of RN-42, Arduino D3 (configure as TX pin)
const int button = 5;
const int xAxis = A0;         // joystick X axis
const int yAxis = A1;         // joystick Y axis
int range = 12;               // output range of X or Y movement
int responseDelay = 5;        // response delay of the mouse, in ms
int threshold = range / 4;    // resting threshold
int center = range / 2;       // resting position value

SoftwareSerial BT(bluetoothTx, bluetoothRx); // args SoftwareSerial(RXpin, TXpin)

void mouseCommand(byte buttons, byte x, byte y) {
  BT.write((byte)0xFD);
  BT.write((byte)0x05);
  BT.write((byte)0x02);
  BT.write((byte)buttons);
  BT.write((byte)x);
  BT.write((byte)y);
  BT.write((byte)0x00);
}

int readAxis(int thisAxis) {
  // read the analog input:
  int reading = analogRead(thisAxis);

  // map the reading from the analog input range to the output range:
  reading = map(reading, 0, 1023, 0, 12);

  /* threshold prevents the mouse from reading small unintentional movements.
  If the output reading is outside from the rest position threshold, use it: */
  int distance = reading - center;

  if (abs(distance) < threshold) {
    distance = 0;
  }

  // return the scaled distance for this axis:
  return distance;
}

void setup() {
  pinMode(button, INPUT);
  pinMode(bluetoothTx, INPUT); // bluetoothTX is equivalent to arduino RX pin
  pinMode(bluetoothRx, OUTPUT);
  Serial.begin(115200);  // Begin the serial monitor at 115200bps
  BT.begin(115200);  // RN-42 defaults to 115200bps
}

void loop() {
  // read and scale the two axes:
  int xReading = readAxis(xAxis);
  int yReading = readAxis(yAxis);
  int buttonState = digitalRead(button);

  // move the mouse:
  mouseCommand(buttonState, xReading, yReading);
  delay(responseDelay);

  if(BT.available())  // If there's data being sent to the bluetooth module
  {
    // Send any characters the bluetooth receives to the serial monitor
    Serial.print((char)BT.read());
  }
}

The problem with getting no response from the mouse was that the bluetooth did not auto reconnect to the computer after powering down. I solved this by sending the command SM,6 for auto reconnect and then R,1 to reboot.