ATtiny85 MIDI IN using SoftwareSerial - Is it possible? I'm trying to read MIDI notes using an ATtiny85 via SoftwareSerial; so far, I've got no success at all.

The ATtiny is using the internal clock, 8Mhz, 5V.
The MIDI keyboard sends clean note on/off messages (tested with a MIDI monitor).
I've tried several test programs, particularly Nick Gammon's, as described here.
I've followed Nick's schematics to build the connector, and I can confirm his program works with an Arduino, but not with the ATtiny.
I calibrated the Tiny with OSCCAL - still no luck.
As far as I can tell, midiSerial.available() is always 0, in every program I've tried.
SoftwareSerial works fine for the purpose of MIDI out.

That's as far as I've got. I'd appreciate any pointers, especially if anyone else could try Nick's code and see if it works.

EDIT

There was an issue with my local version of SoftwareSerial. I had commented out code so that I could use pin change interrupts in my MIDI out program, but those interrupts are essential for MIDI input. Once I uncommented the code, all the programs I tested worked, so it is indeed possible to receive MIDI using an ATtiny.

That said, I've tried four keyboards as inputs and only one has worked so far, a Korg 01/W proX. The same happens when I load the MIDI code directly in the Arduino, so based on the answers below I will try a different optocoupler, and post my results here for the sake of improving on the answer.

Here's the schematics I was talking about:

I have done tests with a normal Arduino with software serial and missed quite a bit of messages, so I would advice to use hardware serial's instead.

For MIDI Out probably it works, but for MIDI In I have bad experiences. Especially when it comes to many messages, like aftertouch/pitch bend etc.

Also, I tried some optocouplers which didn't work well (like 6N137). I now use H11L1 optocouplers (they are white compared to most black ICs) and work perfectly.

You already checked the clean note on/note off ... are you sure it doesn't send active messages?

Below the schematic as I use it.. It does not matter if an STM32 or Arduino is used. Actually I haven't checked if H11L1 are 3.3V or 5V but they seem to work on both.

simulate this circuit – Schematic created using CircuitLab


ATmega 2560 with Arduino bootloader running issue I have designed a board based on an ATmega2560 chip and I burned the bootloader by following this tutorial.

Now I am able to load Blinky and other programs using an FTDI cable. But the issue I am facing right now is the controller runs Blinky fine if I leave the FTDI connected there. If I disconnect the FTDI cable and power-cycle the board it is not running Blinky. If I connect the FTDI, right away it starts blinking.

It looks like something is wrong with my RESET pin connection? Here is what my RESET circuitry looks like:

I also have tried by removing D1 diode but no luck !

The issue was there was some noise on RX Pin of the chip and because of that when it is powered on in bootloader it was stuck at that place. And it was working good with FTDI because RX gets proper connection with my FTDI.

Solution:- Connect 10K pull-down on RX pin resolved this problem.


Why is Serial.print working when nobody receives the data? I have a kind of theoretical question. Let's have an Arduino Uno connected through USB that does a lot of Serial.print-ing. Then I disconnect it and I don't see anything on the Serial monitor, but the Arduino is still working. I can judge by the blinking lamps and so on.

Now I see that all printing goes through HardwareSerial::write from the Arduino core. There is this statement:

  // If the output buffer is full, there's nothing for it other than to
  // wait for the interrupt handler to empty it a bit
  // ???: return 0 here instead?
  while (i == _tx_buffer->tail)
    ;

It means that if the output buffer is full, the Serial.print will hang there eternally. However this doesn't happen. I guess somebody is consuming the data and to be more precise in ISR(USART_UDRE_vect). It seems as the only place where within interrupt _tx_buffer->tail can be changed. Otherwise the code would loop endlessly in HardwareSerial::write. This interrupt USART_UDRE_vect should be raised only when the Data Register is empty.

My question is - who is consuming the sent data? Is that done by some USART_to_USB drivers? Or am I missing some part of the picture?

Regards,
Boyan

The USB-UART bridge is, if it can. And if it can't, no one cares. A UART is asynchronous, hence it doesn't care if anyone consumes it; as long as it has sent the data, that's all it cares about. There can be additional checks to see if the other side is able to receive data, but that is not implemented on the Uno.


Does Anemometer consumes power? I planning to add an anemometer to my small solar weather station.
I designed this system to run from a single 3.7v rechargeable battery and a solar panel so I have to calculate in more power drain.

What I don't really understand is do these anemometers consume any external power or just give out a voltage by themselves?

This one doesn't even have consumption specified:

https://www.adafruit.com/products/1733

For this Supply voltage : 5V - 24VDC:

http://www.ebay.com/itm/JL-FSX2-4-20MA-0-5V-Output-Wind-Speed-Sensor-Wind-Speed-Transmitter-Anemometer-/331521148973?hash=item4d3033482d

If it runs on electricity it definitely consumes power, its only how much the real question is.

Since you are working with electronics I am going to assume that you have a multimeter, if you dont have one. Its about time you did, doesnt cost much and will save you a ton of time debugging.

Nearly every multimeter has an onboard ammeter (the accuracy will be mentioned in the instructions manual). You can use this to determine the current consumed, have a look at a tutorial from sparkfun on how to do this


Invoke a method in the main sketch from within a library I need to use a specific library that issues error messages in the form of String texts. The library uses the Serial.println() function to send the messages to the Arduino IDE's serial monitor.

The problem is that I have the Serial lines from the Arduino linked to another device, therefore I can't use the Serial Monitor to see the messages. I have a method in the Main Arduino sketch that sends any String text msg generated to another device using Udp commands (wireless). This device is connected to a serial monitor unit.

My question is: How can I invoke the Udp method inside the main sketch of the Arduino program from within the aforementioned library? This would help me to convert the Serial.print() text messages from the library directly into Udp messages to be able to visualize them.

The Udp method I'm using is declared as void UdpSend(String msg) in the Arduino sketch. I'd like to use something similar inside the library to wrap the text msg and send it over to the method on the main program.

Any example or link to get this information will help.

EDIT1:

@Majenko,

On the target library, added:  void libUdpSend(const char *libMsg);
On the sketch, I added this method (Udp comm handler):

 void libUdpSend(const char *libMsg)
 {
   Udp.begin(localPort);
   Udp.beginPacket(Udp.remoteIP(), localPort);
   Udp.write(libMsg);
   Udp.endPacket();
   delay(40);
 }

Added this line on the library (right after the declaration on 1.) to test through the remote serial interface:

libUdpSend("String wrapper has been implemented SUCCESSFULLY!");

When trying to compile linking the library, the following exception occurrs:

  error: expected constructor, destructor, or type conversion before '(' token
  libUdpSend("String wrapper has been implemented SUCCESSFULLY!");

I then switched to String as this is the type I want to wrap, Same steps:

On the target library, added:  void libUdpSend(String *libMsg);
On the sketch:

void libUdpSend(String *libMsg)
{
  Udp.begin(localPort);
  Udp.beginPacket(Udp.remoteIP(), localPort);
  Udp.write(libMsg.c_str());
  Udp.endPacket();
  delay(40);
}

Now the error message says:

  request for member 'c_str' in 'libMsg', which is of pointer type 'String*' (maybe you meant to use '->' ?)

I am not an expert on pointers so I'd need some help on how to assign the pointer as argument on the UdpWrite function using the '->' command proposed by the compliler?

Let me know your thoughts on this.

The connection between a sketch and a library is not one-way as many suppose.  Things can go quite happily in both directions.

What you are proposing is something I do quite often when developing a library and I need to get some debugging information out of the library. Yes, it's possible to directly use Serial in the library, but that's something I don't like, and often isn't appropriate anyway, as in your situation.

However, doing it the way you propose (and I use) is actually very simple.

You just make your function in your sketch and tell the library to use it.

For example, in your sketch:

void debug(const char *msg) {
    Serial3.println(msg);
}

And in the library add the line:

void debug(const char *msg);

Then at any point in the same file (or translation unit) you can use

debug("I am here");

That is assuming that the file that you are using it in is a C++ file (.cpp).  If it's a C file (.c) then you have to treat things very slightly differently.  You see, C++ makes a mess of the function names (even vanilla functions like that) which means they can't be seen by C files.  So you have to tell the compiler "I'd like this to be usable in a C file, please".

Which you do with a special "extern" wrapper around your function:

extern "C" {
    void debug(const char *msg) {
        Serial3.println(msg);
    }
}

And then debug() is usable in a C file in the same way as above.

However now it won't work in a C++ file...  (round and round we go...)

Simple to fix: add the extern "C" to the prototype in the C++ file:

extern "C" {
    void debug(const char *msg);
}

If you want to include your "extern" in a header file that could be included into either C or C++ files it's very common to use a construct such as:

#if defined(__cplusplus)
extern "C" {
#endif

void debug(const char *msg);

#if defined(__cplusplus)
}
#endif

That will add the extern "C" wrapper for C++ files (identified by the presence of the macro __cplusplus) but omit it for C files.

I have used "const char *" as the parameter for this example, but you can choose whatever parameters are appropriate for your usage.


Logic Gates Identifier I want to build a program which identifies logic gates connected to Arduino, by testing the output with changing the input voltage...

Here is the code:

int output1 = 0;   //Change output pins HERE
int output2 = 1;   //and HERE
int input = 2;     //Change the input pin HERE, where we will read the data (0 or 1)

void setup() {
  pinMode(output1, OUTPUT);
  pinMode(output2, OUTPUT);
  pinMode(input, INPUT);
  Serial.begin(9600);  // Start serial communication at 9600 bps
}

void loop() {
  int result[12];
  for(int i = 0; i < 2; i++) // For failure test, it runs 3 times
  {
    digitalWrite(output1, LOW);
    digitalWrite(output2, LOW);
    delay(1000);             //Wait for 1sec
    result[i * 4] = digitalRead(input);
    digitalWrite(output1, LOW);
    digitalWrite(output2, HIGH);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 1] = digitalRead(input);
    digitalWrite(output1, HIGH);
    digitalWrite(output2, LOW);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 2] = digitalRead(input);
    digitalWrite(output1, HIGH);
    digitalWrite(output2, HIGH);
    delay(1000);             //Wait for 1sec
    result[i * 4 + 3] = digitalRead(input);
  }
  if(result[0] != result[4] && result[0] != result[8] && result[1] != result[5] && result[1] != result[9] && result[2] != result[6] && result[2] != result[10] && result[3] != result[7] && result[3] != result[11]) // See if the results don't matches...
  {
    Serial.println("Input read error, please try again!");
  }
  if(result[0] == 0 && result[1] == 0 && result[2] == 0 && result[3] == 1) // AND gate
  {
    Serial.println("This is an AND gate");
  }
  else if(result[0] == 0 && result[1] == 1 && result[2] == 1 && result[3] == 1) // OR gate
  {
    Serial.println("This is an OR gate");
  }
  else if(result[0] == 1 && result[1] == 1 && result[2] == 1 && result[3] == 0) // NAND gate
  {
    Serial.println("This is a NAND gate");
  }
   else if(result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 0) // NOR gate
  {
    Serial.println("This is an NOR gate");
  }
  else if(result[0] == 0 && result[1] == 1 && result[2] == 1 && result[3] == 0) // EXOR gate
  {
    Serial.println("This is an EXOR gate");
  }
  else if(result[0] == 1 && result[1] == 0 && result[2] == 0 && result[3] == 1) // EXNOR gate
  {
    Serial.println("This is an EXNOR gate");
  }
  else // If there is no match...
  {
    Serial.println("This is not even a gate");
  }
}

It always gives back 1s... I have tested with leds, it works perfectly by changing the input, but as soon as serial.begin is declared in setup, it fails to work, the just stays on and I said, the program just gives back 1s.

What I'm missing?

Thanks!

Arduino uses pins 0 and 1 for Serial. Use other pins in your sketch


What type of hardware could make a ball tilt or roll? I wanted to know what type of component or module I could use to make a hollow ball move.  I have these hollow plastic balls (think empty easter eggs) that I was going to put a nano in and a sound detector and was just hoping to just get it to move.  I prefer a sort of a tilt left and right effect, but if it just rolls randomly that would work as well.

I was thinking just a simple vibration, but it doesn't really shift the ball at all, so I'm at a loss without building something quite complex with magnets or something.  Perhaps a motor stuck to the side?

The ball moves are made by a simple physics principle called Conservation of Angular Momentum. The angular momentum is a property that has any object that rotates and is proportional to its mass and velocity.
To make a ball move you should play with this momentum, using its simplest application, the mechanical gyroscope.
The mechanical gyro is made of a heavy disc rotating at high speed, modulating its velocity you can change the momentum and create a force that will move your sphere.


Change max and min read value of potentiometer I'd like to know if there is a function or some way to define min and max value to potentiometer, for example: I'm using a mechanical part that only tour the potentiometer a little bit, what means the potentiometer doesn't start in the beginning and doesn't finish in the end. So, how can I make this space the potentiometer tour means 0 to 255 the start to end, respectively?

You cannot declare that the min and max values of a potentiometer are x and y. What you can do is map() the values of the potentiometer to your own desired scale.

To do this, you'll have to get the following values:

Minimum value of the potentiometer, pMin
Maximum value of the potentiometer, pMax

But these values aren't what you want. For example, what you want is pmin to be 0 and pMax to be 100. So, you'll have to scale pMin and pMax to those values.

For this, you use the map() function. What map() does is changing the value in a given scale, to that of another scale. Let's get some example code:

int pMin = 14;  //the lowest value that comes out of the potentiometer
int pMax = 948; //the highest value that comes out of the potentiometer.

int x = 0;  //we will use this value to store the readings of the potentiometer

void setup(){
  Serial.begin(9600); //Serial monitor can be used to check the values
}

void loop(){

  x = analogRead(A0); //connect the potentiometer to the A0 pin of the Arduino

  Serial.print(x);  //prints the original reading

  x = map(x, pMin, pMax, 0, 100) //take the value of x, compared it to the scale of the potentiometer pMin to pMax, and translate that value to the scale of 0 to 100

  Serial.print("\t"); //a tab to make the reading more easy
  Serial.println(x);  //post mapped value, println is a linebreak as well
  delay(100); //so we don't post to much in the serial and you can read data better.
}

With this example you can clearly see how your potentiometer behaves and how you can use the 'weird' values from its readings in a useful way for your projects.


Reading force from an FSR in Newtons I hope I'm in the right place to ask, I couldn't find anything so I ask here, please tell me if I missed some relative topic.

I was following this tutorial : https://learn.adafruit.com/force-sensitive-resistor-fsr/using-an-fsr#in-depth-code-for-analog-fsr-measurements
and the only difference is that I have a potentiometer instead of a 900K resistor. I put it to 14350 Ohms because it fits the tutorial just above the last one, on top of the same page.
So here is the thing : I want to know the force in Newtons but the values I end up with are clearly wrong. A medium touch on the FSR is already > 3 Newtons, and it changes a lot when I turn the potentiometer to a higher resistance (and changing the value of that pota in the code too) : same force applied, different value of that force on the screen.

I know nothing about elecs so I would also like to know more about this part :

// Use the two FSR guide graphs to approximate the force
if (fsrConductance <= 1000) {
  fsrForce = fsrConductance / 80;
  Serial.print("Force in Newtons: ");
  Serial.println(fsrForce);
} else {
  fsrForce = fsrConductance - 1000;
  fsrForce /= 30;
  Serial.print("Force in Newtons: ");
  Serial.println(fsrForce);
}

Where does the /80 and -1000 then /30 come from ? Why is it a different operation and not just only different values ?
I'm using the same FSR but with 3.3V. I have the same graph as this one : https://learn.adafruit.com/force-sensitive-resistor-fsr/overview#how-to-measure-force-slash-pressure-with-an-fsr

I would really appreciate clear and simple explanations. Thank you by advance !

Sparkfun also sells FSR's and they explain it better: "Use them to sense if it’s being squeezed, but you may not want to use it as a scale".

On that Sparkfun page is also a datasheet. It's inaccuracy is 25%, and that is only when the force is applied evenly. When someone presses it with a finger, the inaccuracy is 50% or more.

The quick-and-dirty calculation in the Adafruit example is just for fun, it is not serious measuring the force in Newton.
There are two different calculations, for 'fsrConductance' above and below 1000. When it is above 1000, the 1000 offset is substracted to start the calculation at zero. The difference in calculation is that for one the value is divided by 80 and in the other divided by 30. It's just a rough calculation to get some kind of force value.

To measure weight or force, you need a load cell.


In ESP-12E NodeMCU, what's the pin number of A0? In ESP-12E NodeMCU, all digital pins can be called with a number. Here is the list:

static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t D9   = 3;
static const uint8_t D10  = 1;

So these two lines of code will do the same:

pinMode (D0, INPUT)
pinMode (16, INPUT)

What's the corresponding number for A0 (the only analog input of this board)?

The numeric value of A0 is 17, as defined here.

But unlike on an Arduino board, you can't use it as a digital pin. It only work for pin numbers 0-16.

If you are using as a parameter for analogRead, the numeric values would be 0 and 17, as seen here.

And as such, these three calls would do the same:

analogRead(A0);
analogRead(17);
analogRead(0);


Powering Atmega328P-Pu externally Please I'm new to Arduino and I need assistance. I'm working on a project which makes use of the ultrasonic sensor to make a certain pin high if a certain distance is attained. When I used the USB port to power it up it worked fine. When I use external power(tried two different 9V microphone battery) it's not giving desired result. Now I want to try using just the Atmega328P on the board externally(separately from the Arduino).

Questions

What could be the cause of the malfunction when I use external 9V battery
what voltage should I connect to the VCC of the Atmega cos I'm scared of damaging it.
Am I going to power the ultrasonic sensor with an entirely different source from the VCC or I can tap from that same VCC source.
Any other information I need to know using the ATmega on its own

1.8 - 5.5V (max)

The datasheet (http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Summary.pdf) will tell you that input Voltage is: 1.8 - 5.5V

That's max of 5.5V so don't use 9V battery without a voltage divider.
To power the chip all you need is voltage to Pin 7 and GND to PIN 8.

16Mhz Crystal Most Likely Required

However, to get it to work after removing the chip from an Arduino Uno board you will also need a 16Mhz Crystal on pins 9 & 10.  You will also need two 22pF capacitors on pins 9 & 10, each connected to ground.

I've written this all up with pictures at my blog: http://raddev.us/arduino/post/2018/07/03/arduino-uno-using-your-atmega328p-u-as-stand-alone

Your final circuit will look something like the following (from my blog article):

Without the Crystal you will most likely find that your sketches don't seem to run.

Note: The red LED is connected just as a blink test (more on that in the article).


Is possible to set a pin faster than digitalWrite? I am currently using arduino library to logically set my digital pins high or low, but I just realized how slowly it actually sets those pins, which is especially problem as i am doing this in a ISR routine. Can't this be done faster by actually acessing the direct port, and setting the current pin?

How do I convert something like this

  digitalWrite(11, !digitalRead(11));

To something faster?

I am using a Arduino UNO..

Yes, it is possible

The atmel chip at the core of the arduinos can set or clear individual pin output levels in a single operation. There are special instructions to do so SBI and CBI- you just need to figure out what C compiles down to those instructions.

Each pin is represented by one bit of a port byte, for pin 11 it's bit 3 on port B.  So you can toggle it with

PORTB ^= _BV(PB3);

or set it with

PORTB |= _BV(PB3);

or clear it with

PORTB &= ~_BV(PB3);

Probably the last two will compile to a single SBI/CBI instruction while the toggle one may or may not, depending on the code and how the compiler optimises it.


Delaying an action inside a function My current function is supposed to play a sound effect, then after the sound effect is done (14 seconds), perform the next action (digitalWrite(CONTROLLINO_R1, LOW)).

if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch) {
  skeleLatch = 1;
  wTrig.trackPlayPoly(2);
  unsigned long currentMillis = millis();
  if((currentMillis-previousMillis) >= 14000) {
    digitalWrite(CONTROLLINO_R1, LOW);
    previousMillis = millis();
  }
}

As it is, it performs both at the same time. I do not know how to correctly implement the delay so that it waits.

Any help would be appreciated. Thank you.

unsigned long triggerMillis = 0;

  if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch)
  {
    skeleLatch = 1;
    wTrig.trackPlayPoly(2);
    triggerMillis = millis();
  }

  if (millis() - triggerMillis >=14000 && skeleLatch)
  {
    digitalWrite(CONTROLLINO_R1, LOW);
    skeleLatch = 0;
  }

This should work, depending on how long your CONTROLLINO_A8 is staying high you might want to invest some more time to set up an interrupt on that pin, to make sure you don't miss a trigger.


Is analogWrite() not affected by blocking codes and/or Interrupts? Well just as the question say, is the analogWrite() function will continue generating near-consistent PWM when it encounters blocking codes or signal interrupts?

Is it the same case for both the classic arduinos(atmega chips) and the new arduinos(SAMD21 chips).

If analogWrite() does get affected by blocking codes, is there a way to create a uninterruptible PWM signal?

is the analogWrite() function
  continue generating near-consistent PWM when it encounters blocking
  codes or signal interrupts?

Yes for 'hardware' PWM used by analogWrite on AVR and SAMD Arduinos. The hardware PWM is handled by wave output of Timers, which are MCU peripherals running independently from CPU and other MCU peripherals.

  Is it the same case for both the classic arduinos(atmega chips) and
  the new arduinos(SAMD21 chips).

yes

  If analogWrite() does get affected by blocking codes, is there a way
  to create a uninterruptible PWM signal?

N/A


LCD Custom Character I am experimenting the write((byte)num) function, and I stumble upon a pre-made custom character. Usually it's on above ((byte)200) or and below ((byte)10000). If anyone else know this, where could I find the list for a specific character?

Hi Welcome to Arduino StackExchange
You can build your own LCD characters if you spend some time with the datasheet and user manuals available
Arduino has a dedicated function here
#include <LiquidCrystal.h>

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

byte smiley[8] = {
  B00000,
  B10001,
  B00000,
  B00000,
  B10001,
  B01110,
  B00000,
};

void setup() {
  lcd.createChar(0, smiley);
  lcd.begin(16, 2);
  lcd.write(byte(0));
}

void loop() {}

here is one example:  from our tool here

From the datasheet:

here is one example where a Heart symbol is created using the built-in Arduino LCD library:
You can play here at our LCD1602 simulator to get a hang of it.  Please leave a message or comment if you have any questions :)


How would I refactor this code, given how similar most of the lines are? I have a set of buttons and a set of NeoPixel LEDs. There's lots of very similar constants (button1pin, button2pin, etc) so there's almost certainly a more efficient way of coding this.

Any ideas?

#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);

// Buttons
const int button1pin = 3;
const int button2pin = 4;
const int button3pin = 5;
const int button4pin = 6;
const int button5pin = 7;
const int button6pin = 8;
const int button7pin = 9;
const int button8pin = 10;
const int button9pin = 11;

const int led1 = 0;
const int led2 = 1;
const int led3 = 2;
const int led4 = 3;
const int led5 = 4;
const int led6 = 5;
const int led7 = 6;
const int led8 = 7;
const int led9 = 8;

void setup() {
  strip.begin();
  strip.show();

  pinMode(button1pin, INPUT_PULLUP);
  pinMode(button2pin, INPUT_PULLUP);
  pinMode(button3pin, INPUT_PULLUP);
  pinMode(button4pin, INPUT_PULLUP);
  pinMode(button5pin, INPUT_PULLUP);
  pinMode(button6pin, INPUT_PULLUP);
  pinMode(button7pin, INPUT_PULLUP);
  pinMode(button8pin, INPUT_PULLUP);
  pinMode(button9pin, INPUT_PULLUP);
}

void loop() {
  if (digitalRead(button1pin) == LOW){
    strip.setPixelColor(led1, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button2pin) == LOW){
    strip.setPixelColor(led2, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button3pin) == LOW){
    strip.setPixelColor(led3, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button4pin) == LOW){
    strip.setPixelColor(led4, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button5pin) == LOW){
    strip.setPixelColor(led5, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button6pin) == LOW){
    strip.setPixelColor(led6, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button7pin) == LOW){
    strip.setPixelColor(led7, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button8pin) == LOW){
    strip.setPixelColor(led8, strip.Color(20, 55, 0, 0));
  }
  if (digitalRead(button9pin) == LOW){
    strip.setPixelColor(led9, strip.Color(20, 55, 0, 0));
  }

  strip.show();
}

#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel strip = Adafruit_NeoPixel(9, 2, NEO_RGBW + NEO_KHZ800);
// The maximum pin number for the buttons
const int MaxButton = 11;
// The value if the pin is not connected to an LED
const int NotConnected = -1;
// The connections from buttons to leds.
const int Connections[MaxButton+1] = {NotConnected, NotConnected, NotConnected, 0, 1, 2, 3, 4, 5, 6, 7, 8};

void setup()
{
  strip.begin();
  strip.show();
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        pinMode(pinNumber, INPUT_PULLUP);
    }
  }
}

void loop()
{
  for (int pinNumber = 0; pinNumber <= MaxButton; ++pinNumber)
  {
    if (Connections[pinNumber] != NotConnected)
    {
        if (digitalRead(pinNumber) == LOW)
        {
            strip.setPixelColor(Connections[pinNumber], strip.Color(20, 55, 0, 0));
        }
    }
  }
  strip.show();
}

I can't test it, so I have no idea if it works, but it should do.


Controlling HDMI Switch via RS232/UART Problem:

I have an HDMI switch that is controllable via RS232

Scenario 1:

Setup: PC connected to HDMI switch using USB -> serial adapter
Test: Opening PuTTY on COM port and sending command "sw i01" from my PC
Results: HDMI switch input changes to port 1 [Good]

Scenario 2:

Setup: Arduino UART port connected to TTL->RS232 adapter connected to serial->USB adapter connected to PC with PuTTY program open on COM port
Test: Sending command "sw i01" from Arduino to PC using code below
Results: "sw i01" prints repeatedly on the Putty terminal [Good]

Scenario 3:

Setup: Arduino UART port connected to TTL->RS232 adapter connected to HDMI switch serial port
Test: Sending "sw i01" from Arduino repeatedly to HDMI switch using code below
Results: HDMI port does not switch from port2 to port1 [Bad]

Hardware:

Intel Galileo Gen 2
SparkFunRS232/TTL Shifter connected to Galileo UART
HDMI switch is IOGear GHSW8141

Code:

[Note: Galileo Gen 2 requires Serial1 for UART communication]

void setup() {
    Serial1.begin(19200);
}

void loop() {
    Serial1.print("sw i01");
    Serial1.write(13);    // CR
    Serial1.write(10);    // LF
    delay(1000);
}

Question:

It seems like Scenario 1 and 2 confirm that the Arduino->HDMI switch communication should work, but it doesn't. Am I missing something regarding physical connectivity? Does manually typing "sw i01" in PuTTY send different commands than I have in the Arduino code?

Your HDMI switcher, and your USB to RS-232 converter speak RS-232.  The Arduino speaks TTL UART.

While the concept behind them, and the overall format of the data, is the same there are major differences:

RS-232 uses a ±10V NRZ signalling method, TTL UART uses a 0-5V signalling method
RS-232 uses inverse logic compared to TTL UART

That means that you need to convert the Arduino's TTL UART to ±10V NRZ with inverse logic in order to communicate with the IOGear.

Fortunately that's a simple enough task using a special interface chip. These are readily available and can be bought for tiny amounts as a breakout board or even a full shield if you like (such as this one from Sparkfun).  The chip is known as a MAX232 in its most common form, though other manufacturers may use different letters.

If you pop on eBay (or your favourite budget seller site) and search for "Arduino MAX232 DB9" (the DB9 is the type of plug on the board - the 9-pin D connector) you will get lots of hits to choose from.


Serial communIcation from OS X app to Arduino Mega I am new to stack overflow. I have a question regarding using the USB serial communication sending data from an OS X app to the Arduino Mega 2560.

What happens is, when I have the Arduino running with the Serial monitor open, then I run the OS X app to send data, the Arduino does receive the data for a few seconds, then it stops.

This is the simplified Object-C code on the Mac side:

-(IBAction)sendData:(id)sender{
    NSString *toSend=[NSString stringWithFormat:@"echo %f > /dev/tty.usbmodem1a1341" ,vector.x];
    //vector is the continuous data generated by the Mac
    const char *toCSend =[toSend UTF8String];
    //converting to c string
    printf("%s", toCSend);
    popen(toCSend, "r");
}

This is the code on the Arduino side:

// Read Serial input:
void setup() {
  // Open Serial commurial1.beginnications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    // wait for Serial port to connect. Needed for Leonardo only
  }
}

void loop() {
  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    } else {
      // if you get a newline, print the string,
      // then the string's value as a float:
      Serial.println(inString.toFloat(), 6);
      // clear the string for new input:
      inString = "";
    }//end of if else
  }//end of while (Serial.available() > 0)
}

I am not sure what the problem, could it be the OS X app send out too much data to quickly? Or could it be the Arduino serial buffer is overflowed?

I really don't know much about serial communication so I don't know what I am missing. Any help will be greatly appreciated.

One problem is here:

  // Read Serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();

    if (inChar != '\n') {
      inString += (char)inChar;
      Serial.read();
    }

Your Serial.available() call guarantees that you have one byte of serial input, but you are attempting to read two of them if the first one is not a newline. This is not valid.

How to process incoming serial data without blocking


Displaying binary to LEDs I've written a program for Arduino UNO and 3 LED lights. The program is supposed to turn an inputted number into binary and then display it on the LEDs, on being 1 and off being 0 I have looked it over quite a few times and don't understand why it is not working as it should. I'm a beginner at working with Arduino so I probably just need a more experienced eye to show me where I have messed up. I have a link to a picture of the Arduino setup below. Thanks!
https://drive.google.com/file/d/0B8k_WNZ3eFOkZHkwNUllTEp4WGM/view?usp=sharing

//setting up lights
const int lightOne = 13;
const int lightTwo = 12;
const int lightThree = 11;

//array of the lights for when printing the binary
int lights[] = {lightOne, lightTwo, lightThree};

void setup() {
  //setting pin modes and starting up the serial monitor
  pinMode(lightOne, OUTPUT);
  pinMode(lightTwo, OUTPUT);
  pinMode(lightThree, OUTPUT);
  Serial.begin(9600);
}

//converts a given number into binary
String binary(int number) {
  String r;
  while(number!=0) {
    r = (number % 2 == 0 ? "0" : "1")+r;
    number /= 2;
  }
  return r;
}

//outputs the binary string to the lights (not expecting numbers larger than     9)
void printBinary(String binaryNumber) {
  for (int i = 0; i < sizeof(binaryNumber); i++) {
    digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));
    delay(2000);
  }
}

void loop() {
  int input = Serial.read();                //get the number
  String binaryNumber = binary(input);      //convert number to binary
  Serial.println(binaryNumber);             //print binary to serial monitor
  printBinary(binaryNumber);                //display number in binary on     LEDs

}

Welcome to SE Arduino!

Long Version

You have a couple of things to look at:

Don't use String class it has too much overhead for Arduino.
Your conversion function is not really necessary because you can convert it on your Serial.println() by specifying binary as output. eg: Serial.println(number, BIN);
The Serial.read returns an integer, but that int only contains a byte (unsigned) value anyway (unless there's nothing to be read, in which case it returns -1). Because you're taking a number (not really relevant) and you want it to be a number on the return, just use int or byte (unsigned: 0 <-> 255) or char (signed: -127 <-> +128).
You could/should/doesn't matter if you use Serial.available() or not, it is a matter for yourself, I usually do, but it's non blocking anyway and if there's nothing there to be read, it'll just continue on anyway. Although if you're not going to use it, you should test for that -1 as what you're doing at the moment is taking that and converting it to binary (which is 0xFF which is everything on). This is one of your major problems in the code (the other is in the Short Version section.
You're using "0" and "1" which are ASCII values, and you haven't indicated how you're getting the number. So it may be ASCII (byte) or actually a byte value. ie, "0" is 48 (dec) or 30 (hex). Whereas a 0 is just zero. Funnily enough, because you're using modulo (%) it doesn't really matter because you're only interested in the lowest nibble, which for the sake of your code, doesn't matter what's encoded at the higher end. ie: 1 (0b00000001) is the same as "1" = 49 (dec) = 0x31 = 0b00110001 when used with %2.
Ditch your delay(2000). Delays are evil* :) You could write the values to the pins all day, you're not going to cause any problems, if you want to output less to your serial port (which you should do), you could do timed outputs back to Serial. ie, do your Serial.println() once a second, or record the values into backup/old variables and compare them, and only print the output if the value changes
The big one is in the next section

Short Version

This is your main problem, on this line:

digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));

I think you need:

digitalWrite(lights[i], (binaryNumber[i] == '0' ? LOW : HIGH));

You already have the pin value encoded in the array, you don't want to add 11 to the index, that's going to throw you above your three light values :)

* Delays are evil: It's a matter of opinion, and that's just how I feel, I actually googled it and this is just a random response. But it contains the crux of what I'd say anyway: http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/


Taking off the chip from Arduino I just uploaded a sketch of a song to my Arduino and it works well.  Could I just take the chip out and hook up speakers to it and a power source to play the song? and just get another chip and put it in the Arduino.

Yes and no.

To elaborate, the sketch you downloaded to the chip has been flashed to internal non-volatile memory. So if you were to move it to another Arduino board or other device with the appropriate support hardware, then it should work just fine.

However, if you're intending to directly hook-up speakers to it and a power source, then I highly doubt it's going to work. You really need some support hardware for the chip (such as an external clock - though I think the Atmega328 has an internal clock, decoupling capacitors, amplifiers for the spearkers, etc.).


Detect movement on moving robot? PIR Sensor I am working on a human following robot project and I am trying to achieve this with 1 Ultrasonic sensor that makes sure the robot won't crash into something and 3 PIR sensors that will detect human movement.

The robot has an Ultrasonic Sensor and a PIR sensor attached to the front and a PIR sensor attached to the right side and another PIR sensor attached to the left side.

If the front PIR reads HIGH, then the robot will move forward. If the left or right PIR reads HIGH, then the robot will start turning in a 360 degree motion to the left/right side and will keep on doing so until the front PIR reads HIGH, and the robot moves forward again.

I am currently working with this build and I am having issues with the sensors. Sometimes they read HIGH when they shouldn't and sometimes they read LOW when they should be reading HIGH.

So my question is, what can I do to help the PIR sensors with getting the correct reading and is it possible to do so while the robot is turning?

Also, how will calibration work here? Am I able to let the robot turn slowly in 360 degree motion so the 3 PIR sensors will be calibrated with the rooms surrounding or is this a dumb question? If so I'm sorry, I am pretty new to PIR sensors.

UPDATE:

Thanks for the help everyone. I have now replaced the side PIR sensors with Ultrasonic sensors. I have kept the front PIR sensor though. It is working a lot better than with the side PIR sensors and I thank you all for your input.

Basically you have a robot and sensors that can detect movement.
There is one caveat though. For the PIR sensors to (non false-positive) detect motion, they have to be stationary (as far as I know).

So with only these PIR sensors it's unlikely that you can track something well.
Tracking something would be done best by using a range/proximity sensor.

The image below, seems to be a cute robot, with eyes.
You could take 3 sensors and place them under an angle (one forward, one forward/left and one forward/right) [picture 2]. Or just have one that rotates (will be more difficult) [picture 1].

You would want the robot to start following anything that comes close (or when one of the sensors sees a difference in distance. And then the robot will try to keep that distance, brake when he gets closer, drive when he gets further.

If that's working, you can implement the sensors at the side, that if suddenly he loses track of the object/person, he'll adjust his alignment so that the middle sensor sees it again. This could also be done by simpler sensors [picture 3]

When the robot gets to close, and the other object doesn't try to run for quite a time, you can make him check for another target. (With a PIR or by rotating and stopping rotating to check range/pir)

I believe this solution is more applicable as with only PIR sensors, as it's usefull to know the range when you're following something. You don't want to bash into it.


How to transfer data from Arduino to some software in computer? My arduino gets some data from sensors and save it into EEPROM. Now, I want that when I connect my arduino to PC there should be a software(like sketch) which can fetch data from arduino's EEPROM processes it and saves it into a file in PC. I am willing to create such a software but how will I then communicate with arduino like Sketch does?

Just use serial communication. Make sure you know which port your Arduino is recognized in your system, make a sketch to send data through Arduino's serial communication and try making a simple Node.js application using serialport package which will receive your data. There is a code sample where you can start from. Just set the port and start receiving data. And that's good, using Node.js you are really close to web tools, so it's easy to migrate your application to web.

It's really simple and you can get it done in a few minutes, even if you have not been introduced to node.

These kind of embedded applications have been accepted by Node.js and there are plenty of robotics projects which use node on the web.

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM0", {
  baudrate: 57600
});

Usually Arduino is recognized as ttyACM0 on Unix-based systems.
With this line of code you establish a serial communication with your board.

Going further you can register events like data, which is fired when data comes from Arduino:

// it opens the connection and register an event 'data'
serialPort.on("open", function () {
  console.log('Communication is on!');

  // when your app receives data, this event is fired
  // so you can capture the data and do what you need
  serialPort.on('data', function(data) {
    console.log('data received: ' + data);
  });
});

In this example your app just receives data and log it to your terminal.


Fingerprint sensor code won't work correctly with LCD 16x2 I am doing a fingerprint sensor that works with a 16x2 LCD. The code works correctly for the fingerprint sensor, but when I enter LCD code, the LCD works but the fingerprint stops working.

I am using an Arduino Uno and an Adafruit fingerprint sensor. Both the fingerprint and LCD are wired correctly and work separately. I have enrolled and tested fingerprints and it worked perfectly until I added LCD code.

#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int getFingerprintIDez();
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup() {
 // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
  Serial.begin(9600);
  Serial.println("fingertest");
  // set the data rate for the sensor serial port
  finger.begin(57600);
  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1);
  }
  Serial.println("Waiting for valid finger...");
}

void loop() {
  getFingerprintIDez();
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK success!
  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
   Serial.println("Unknown error");
    return p;
  }

  // found a match!
  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with confidence of ");
  Serial.println(finger.confidence);
}

// returns -1 if failed, otherwise returns ID #
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;
  // found a match!
  Serial.print("Found ID #");
  Serial.println(finger.fingerID);
  Serial.print("This Finger print related to : ");
  switch(finger.fingerID){
   case 0:
     Serial.println("Subhy Mesmar");
     break;
   case 1 :
     Serial.println("Amjad Mesmar");
     break;
  }
  return finger.fingerID;
}

In this image the fingerprint sensor works without LCD code:

And in this one the LCD works after adding code but the fingerprint sensor stopped working:

You have pins 2 and 3 used by both the LCD and the SoftwareSerial used for the fingerprint sensor.

Use different pins for one or the other.

Worth looking at the Software Serial reference to understand more about how it works.


Does an Arduino get worn out by too much command execution? Excuse me if it is a silly question, but I couldn't find an answer.

I've been wondering for a while whether an Arduino (or generally any other micro-controller) gets happy if the code is light and it does not have to execute too much operations. Does a code that has too many ifs, too many loops and all sort of complicated calculations wear out an Arduino sooner than a code that just blinks an LED?

No, the code doesn't "wear out" the MCU. In general no matter what you are doing roughly the same level of activity is being performed. Even delay() does lots of work while it's "idling".

There are commands to make the CPU do less - place it in an IDLE or SLEEP mode - but these are used to save power rather than to reduce "wear" on the MCU.

Of course there are specific things that do have a limited lifetime and you can only use them a limited amount of times - things like writing to EEPROM and writing to the Flash memory - so you don't want to be doing those all the time. Other than that, no, no matter what you are doing it doesn't wear the MCU out.


Uploading Temperature data (DHT22) to Thingspeak with an ENC28J60 So, I've gotten my module working pretty well. It logs data from the DHT22 and sends it to a 192 address on my LAN. However, I'd like to log and graph the data.

I figured thingspeak is a decent platform for that. However, I have no experience doing so, and I'm not sure where to start. All the examples use the "official" arduino shield. I've only found ONE example bit of code, but it uses the Dallas One Wire temp module. Link

I'm in over my head, and have no idea how to switch from the One wire to the DHT22. Thanks for the help!

I'm using a clone arduino pro mini, 5V 16mhz, 328.

If there's a better platform than thingspeak, I'm open. All I want to do is graph and visualize the DHT22 sensor readings.

Try this:

/*
| Post temp. values from a DS18B20 to ThingSpeak using the Ethercard interface based on the
| ENC28J60 chip.
| Based on the Ethercard example from www.jeelabs.org
| Phil Grant Jan 2014
*/
#include <EtherCard.h>
// change these settings to match your own setup
#define APIKEY  "xxxxxxxxxxxxxxxx"

//DHT Setup
#include "DHT.h"
#define DHTPIN 2     // what pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);

// ethernet interface mac address, must be unique on the LAN
byte mymac[] = { 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX };

char website[] PROGMEM = "api.thingspeak.com";

byte Ethernet::buffer[700];
uint32_t timer;
Stash stash;

void setup () {
  Serial.begin(57600);
    dht.begin(); //Initializate DHT
  Serial.println("\n[webClient]");

  if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
    Serial.println( "Failed to access Ethernet controller");
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");

  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  if (!ether.dnsLookup(website))
    Serial.println("DNS failed");

  ether.printIp("SRV: ", ether.hisip);
}

void loop () {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 60000; //Transmit every minute
    delay(2000);  // Wait a few seconds between measurements.
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity(); // Read temperature as Celsius (the default)
  char h_buffer[10];
  String Hstring = dtostrf(h,0,5,h_buffer); //Convert Humidity value to String

  float t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true)
  //float f = dht.readTemperature(true);
  char t_buffer[10];
  String Tstring = dtostrf(t,0,5,t_buffer); //Convert Temperature value to String

    byte sd = stash.create();
    stash.print("field1=");
    stash.println(Hstring);
    stash.print("&field2=");
    stash.println(Tstring);
    stash.save();

    // generate the header with payload - note that the stash size is used,
    // and that a "stash descriptor" is passed in as argument using "$H"
    Stash::prepare(PSTR("POST /update HTTP/1.1" "\r\n"
                        "Host: $F" "\r\n"
                        "Connection: close" "\r\n"
                        "X-THINGSPEAKAPIKEY: $F" "\r\n"
                        "Content-Type: application/x-www-form-urlencoded" "\r\n"
                        "Content-Length: $D" "\r\n"
                        "\r\n"
                        "$H"),
            website, PSTR(APIKEY), stash.size(), sd);

    // send the packet - this also releases all stash buffers once done
    ether.tcpSend();
  }
}


Purpose of USB (FTDI) and ICSP connectors As an Arduino newbie I am a little bit confused about possible ways of programming and communicating with this device. I have done some research and it seems that:

ICSP is used for programming with a bootloader in MCU.

The USB (FTDI) port is used (mostly) for sending text messages to the PC and programming without a bootloader.

Am I right? How can I detect whether I have a bootloader installed (Uno R3 clone)? Thank you very much!

The ICSP is used for 'bare metal' programming. This what you'd use if you wanted to replace or remove the bootloader, change the clock oscillator settings, or program the device as a bare 328.

The USB port is for communicating with a program running on the Arduino. When it's first booted, the bootloader program checks to see if there's any activity on the serial link from the Arduino host program on a PC. If there is, then it allows downloading of a program from it. If not, it continues on to the last code that was programmed into it.

The easiest way to see whether a bootloader is installed is simply to start it up with the PC host, and see whether it can talk to it.


Ethernet shield not getting IP I am just running the below DHCPAddressPrinter sketch in Arduino example to setup EthernetShield with MAC and IP

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

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

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

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

void loop() {

 }

After uploading the sketch to arduino,below is the output shown in console

Sketch uses 13,614 bytes (42%) of program storage space. Maximum is 32,256 bytes.
Global variables use 539 bytes (26%) of dynamic memory, leaving 1,509 bytes for local variables. Maximum is 2,048 bytes.

And there is nothing shown in Serial monitor
This is the image of Ethernetshield's some leds glowing after connecting to Router.
My router is Binatone Wireless ADSL2+ Router.

I checked arp -a,

C:\Users\Radhamani>arp -a

Interface: 192.168.1.6 --- 0x3
  Internet Address      Physical Address      Type
  192.168.1.1           6c-fd-b9-24-c6-fe     dynamic
  192.168.1.255         ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static
  255.255.255.255       ff-ff-ff-ff-ff-ff     static

Interface: 192.168.198.1 --- 0xe
  Internet Address      Physical Address      Type
  192.168.198.255       ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static

Interface: 192.168.234.1 --- 0xf
  Internet Address      Physical Address      Type
  192.168.234.255       ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static

Complete result of ipconfig:

Wireless LAN adapter Wi-Fi:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::901:3297:48ad:9e7d%3
   IPv4 Address. . . . . . . . . . . : 192.168.1.6
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1
Ethernet adapter VMware Network Adapter VMnet1:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::c954:40b2:c8c1:de0%14
   IPv4 Address. . . . . . . . . . . : 192.168.198.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
Ethernet adapter VMware Network Adapter VMnet8:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::2837:7e01:c799:d627%15
   IPv4 Address. . . . . . . . . . . : 192.168.234.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

Serial.println in the program is not printing anything.Looks like Ethernet shield is not getting IP.I am not sure where I am wrong.Please help me to fix this issue

Based on the image .. i see that the programmer pins at the back of the shield and the arduino aren't connected properly.. That might be the error or at least happened with me.
Apart from that, certain network need to identify the mac address from a look up table and if the shield mac address matches, then only network transactions are allowed.
Also i suggest you to drop the virtual machine mac address and networking protocols and try upon the base OS which you have on your computer.


RF24 communication between Leonardo and Micro not responding I have Arduino Leonardo and Micro. I can't manage them to communicate via nRF24L01. I made a receiver and sender sketch to test it and can't see any respond. I tested the same code on two arduino nano and they work fine.

I connected the pins correctly using the ICSP pins in Leonardo and corresponding pins (not ICSP) dedicated for SPI in Micro.

Please could someone tell me what am I missing in porting sketch from nano-nano to leonardo-micro?

Here are the sketches:

PS some additional channels are left to see what I expected from working sketch.

Receiver module:

//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openReadingPipe(1, addresses[0]);
  radio.openReadingPipe(2, addresses[1]);
  radio.openReadingPipe(3, addresses[2]);
  radio.openReadingPipe(4, addresses[3]);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  while (radio.available()) {
    char theMessage[13];
     radio.read(&theMessage, 13);
     Serial.println(theMessage);
     if(theMessage == "testingsend"){
       //this is removed in nano
      digitalWrite(13,HIGH);
      delay(50);
      digitalWrite(13,LOW);
     }
  }
}

And the sender:

//NRF24
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
RF24 radio(9, 10);
byte addresses[][6] = {"1Node", "2Node", "3Node", "4Node"};

int channel = 1;

void setup() {
  // put your setup code here, to run once:
  radio.begin();
  radio.setAutoAck(1);
  radio.setRetries(15, 15);
  radio.openWritingPipe(addresses[channel]);
}

void loop() {
  // put your main code here, to run repeatedly:
  char theMessage[13] = "testingsend";
  radio.write(theMessage, sizeof(theMessage));
  memset(theMessage,0,sizeof(theMessage));
  delay(300);
}

Ok I solved the issue, somehow I had to use 10 uF capacitor instead of 4.7 uF


Is there complex application examples out there that can be considered best practice material? I'm coming from a web environment and not that fluent in C++. About to start a moderately complex dev on an ESP32 device.

I know that there is hundreds of arduino libraries out there but I haven't found a lot of complex actual application examples.

I'm mostly interested in the file structure, separation of concerns and other C++ tweaks that should be considered best practices when coding on embedded devices in a more robust way.

I found the ardupilot GitHub project to be very interseting to look into, but its quite big, and I'm not sure if it would be considered well written code as I can't judge myself.

Can you recommend other great projects to look into?

If you are used to OO (which I guess since you like separation of concerns), do not use the Arduino IDE, since it is very hard to work with multiple files. Instead use e.g. vMicro for Visual Studio.

Separation of concerns (using C++) for the Arduino is not much different than in other languages. C++ has the notion of classes, and fields/functions can be made private, protected and public (simplified).

However, C++ itself is not so easy to learn, mostly because of pointers and related issues. However, it's something to dive in when you want to learn something new.


Single pin as input and output Is there a way to set an Arduino pin as being both an input, and an output?

I was looking at tristates, I'm not sure if that is related, or if there is some other method.

Perhaps I can try switching states rapidly. on one pin. I'm just not familiar with how to do it, and I don't see anything about it on the Arduino site.

This is a function of other microcontrollers, such as PICs, but I'm not sure about AVRs and Arduino types.

The source code for the 1-Wire protocol is a great place to start when learning how to use a single pin for both input and output.

See also chap. 18. I/O-Ports in the ATmega328p datasheet.

Cheers!


Brownout detector triggered I'm running a pretty basic setup. When I run a small program just doing some serial.println, it works fine, when I try to do operations that needs more power, the brownout detector gets triggered. I'm running my chip on an ok buff power supply so I don't get what the problem is.

The ESP typically runs on 3.3 Volt, not 3.0 Volt.

Secondly, it looks like the board has a voltage regulator, all power goes through the voltage regulator. If that's the case the voltage you need to supply must be lower that the drop-out voltage of the regulator (which is typically around a volt).


Serial port /dev/cu.usbmodemfa131 vs /dev/cu.usbserial-A702NY8S On Mac OSX Mavericks, why does Arduino Uno uses serial port named /dev/cu.usbmodemfa131 while Arduino Nano uses /dev/cu.usbserial-A702NY8S?

Are they using different FTDI drivers?

Drivers are different. On older boards, such as Duemilanove you may need to actually download serial drivers to talk to them at all in Lion, Mountain Lion, Mavericks.
There's some discussion of that problem here.


"missing filename" compilation Error I've recently got back to my Uno. I tried compiling my program and got the following error:

Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"

avr-g++: error: missing filename after '-o'

exit status 1
Error compiling.

This happens on any of the programs I've tried to compile/upload.
I've searched around on Google but I have gotten no definite answers and how to fix this or what has caused this? Does anyone have an idea on what I could do?

I had same problem. You should download Arduino IDE 1.6.8

https://www.arduino.cc/en/Main/Software


What is the equivalent of this old SPI code using the current SPI library? I see some old library code that initializes SPI this way:

    SPI.begin();
    SPI.setClockDivider(2);

It does not use beginTransaction/endTransaction blocks, and setClockDivider is now deprecated. The current way to use SPI is to use transaction blocks where you pass the settings in.

What is the equivalent to this code using transaction blocks? Also, since the other settings (max speed, data order, data mode) aren't specified in the above code, there must be defaults. What are these defaults?

The default is:

Mode 0
MSBFIRST

Not sure on the default speed. But:

setClockDivider() sets a speed relative to the system clock. So it's impossible to say what speed that will be since it'll be different on 8MHz boards compared to 16MHz.

setClockDivider(2) would be the same as using F_CPU/2 as a speed.


Arduino and Solenoid Water Valve I use Arduino UNO and two SPST Relay (Wemos Mini D1 Relay) to make the reverse polarity circuit. I use this circuit to open and close the Solenoid Water Valve (SWV), which work with 9 to 12 volt. The connections are as follows:

NO (Relay1) --> NC (Relay2) --> +12 Volt
NC (Relay1) --> NO (Relay2) --> 0
D1 (Relay1) --> D1 (Relay2) --> Digital pin 3 of Arduino
COM (Relay1) --> SWV1
COM (Relay2) --> SWV2
GND Relay1) --> GND (Relay2) --> GND of Arduino
5V (Relay1) --> 5V (Relay2) --> 5 Volt of Arduino

the circuit work perfectly with Arduino boar. But the problem is that when I use ATMEGA328p-PU on breadboard as explained in LINK, Relays are not working properly. Actually, relays connecting and disconnecting continuously when ATMEGA328p sends 1 to D1 pins of Relays.

The point is when I de-attach the SWV, relays work properly. but if the SWV is connected it still is not working.

I've checked the connection many times and they are correct.

I used the following code in arduino:

int Relay = 3;
void setup() {
  // put your setup code here, to run once:
  pinMode(Relay, OUTPUT);
  digitalWrite(Relay, LOW);

}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
  digitalWrite(Relay, HIGH);
  delay(2000);
  digitalWrite(Relay, LOW);

}

Any help is highly appreciated.

Thanks in advance.

The problem is most likely EMI (electromagnetic interference) from the switching of the inductive load by the relays.

The fact that you have your setup on a breadboard means that each and every pin of the ATMega328 is connected to a little antenna. That massively increases its susceptibility to falling prey to EMI.  Add to that the fact that there is absolutely no decoupling of the power supply (thanks to Arduino producing shoddy worthless tutorials) makes the whole chip very fragile.

When running with a real Arduino board you have decoupling on the power which helps to reduce induced power rail bounce which can cause the chip to fail.

There are two things that can help mitigate this:

Add decent decoupling to the ATMega328

This means adding capacitors between each VCC pin and ground. At the bare minimum a 100nF capacitor on each VCC pin is needed. Additionally a 1nF capacitor can be beneficial. A 10µF capacitor should also be added on the breadboard's power rails to act as a board-level reservoir.

Snubber networks on the switching

A snubber network, in its most simple form, is a resistor and capacitor in series.  It is placed across the switching terminals of a device that is switching an inductive load to absorb the sudden spike of back-EMF from the collapsing magnetic field whenever the load is switched off.

simulate this circuit – Schematic created using CircuitLab

Note that the capacitors here should be rated for at least 400V since the voltages involved are quite high.


Arduino Nano no serial port for MacBook Air 2013 Problem

I have an Arduino Nano connected via a USB cable (Type A to Mini Type B) to my MacBook Air (Mid 2013 Model). The PWR LED is on while the arduino is connected.

Opening the Arduino software, pulling down the Tools > Serial Port menu does not show me a valid serial port. All I see is:

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

What I've tried and did not work

I have installed the correct FTDI driver (v2.2.18). x64 for my MacBook Air's Corei5, file FTDIUSBSerialDriver_10_4_10_5_10_6_10_7.mpkg. Restarted after installation.
Tried connecting arduino to both USB ports on my Air.

More Info

Running Mac OSX 10.10 Yosemite
Same arduino and cable work when connected to a Windows machine or a Raspberry Pi.

If it helps, I can see the USB Serial in my Apple Logo > About This Mac > System Report under Hardware > USB

USB2.0-Serial:

  Product ID:               0x7523
  Vendor ID:                0x1a86
  Version:                  2.54
  Speed:                    Up to 12 Mb/sec
  Location ID:              0x14100000 / 8
  Current Available (mA):   500
  Current Required (mA):    Unknown (Device has not been configured)

I'm out of ideas and options. Any help would be greatly appreciated.

Thanks in advance :)

This solved it for me.

Download this driver
Install it
Run sudo nvram boot-args="kext-dev-mode=1"
Reboot

Serial ports now showed up in the Arduino IDE and also when I used ls -1 /dev/tty*

Hopes this helps someone.

Reference: This thread


How to use external libraries in CLion I would like to use the external libraries that are downloaded by Arduino IDE into the default sketchbook location (~/Arduino/libraries/).

If you open Library Manager in Arduino IDE and if you install an external library (e.g DHT sensor library 1.3.7 and its dependency Adafruit Unified Sensor 1.0.3) then it will be downloaded to the sketchbook location and you can use them freely in case of writing code in Arduino IDE.

However I really like auto code completion, managing source code in GIT repository, formatting source lines, etc. which functionalities are not provided by Arduino IDE, so I changed to CLion.

I have installed CLion and Arduino Support 1.4.4 Plugin and created a new Arduino Sketch Project.

Project Structure:

.
+--cmake
   +--Platform
      +--Arduino.cmake
   +--ArduinoToolchain.cmake
+--libs
   +--Adafruit_Sensor
      +--Adafruit_Sensor.h
      +--library.properties
      +--README.md
   +--DHT
      +--DHT.cpp
      +--DHT.h
      +--DHT_U.cpp
      +--DHT_U.h
      +--keywords.txt
      +--library.properties
      +--README.md
+--CMakeLists.txt
+--first_test_project.ino
+--User_Setup.h

first_test_project.ino:

#include <Arduino.h>
#include "User_Setup.h"
#include <libs/Adafruit_Sensor/Adafruit_Sensor.h>
#include <libs/DHT/DHT.h>

DHT *dht;

void setup() {
    dht = new DHT(7, DHT22);
}

void loop() {

}

So I have copied over the downloaded libraries from ~/Arduino/libraries folder to the project folder under libs folder.

When I try to upload the code to Arduino Board I am getting the following in the log:

undefined reference to `DHT::DHT(unsigned char, unsigned char, unsigned char)'

Could somebody please explain what is wrong here.

Thank you very much!

Did you add your libraries to the cmake files?

I don't have any experience with CLion but undefined reference normally means that
the linker couldn't find the function/class your are using.

So make sure the libraries are compiled and the linker knows where to find the object files.


Arduino and reading from multiple USB connections I'm sending up a high-altitude balloon with an onboard Mighty Ohm Geiger Counter and some other sensors, all of which will be managed by an R Pi B+. I'll collect and store the data with the R Pi; all of that's fine.

In order to track and recover it, I'm using the HABDuino shield on an Arduino. It uses the APRS system and sends back short messages, giving the altitude, internal temp, my callsign, and coordinates. I'd like to add the Geiger counter's data to that, but I'll need to get it from the R Pi.

Currently, I'm using an FTDI Friend to connect the Gieger counter to the R Pi, and getting the data from the serial port. I see here that I can connect the Arduino and Pi vai USB, but... since there's already a USB connection to the Gieger counter, will there be a conflict? Is that something that I can work around?

Thanks for the help!

The FTDI should be showing up as /dev/ttyUSB0 on the Pi.

If you connect an Arduino as well it will show up as /dev/ttyACM0.

If you don't have enough USB sockets then just add a USB hub.


Multithreading with Arduino Well I've just started learning the concept of multithreading with C++ and immediately a bunch of questions came to mind about the possibility of using multithreading with microcontrollers in general and Arduino specifically.

So, is it possible to use multithreading on any type of Arduino boards?

In Cosa you can find the following support for concurrent programming:

Events, interface interrupt service routines
Jobs, delayed, periodic or alarm functions with us, ms and seconds level timers (Watchdog, RTT or RTC).
FSM, object-state function
ProtoThreads, object-state pointer
Threads, Semaphores, etc, multiple stacks
UML Capsules and Connectors, dependency driven programming

There are plenty examples on how to use these. A good starting point is the Blink sketches. There is even a multi-threading Blink example with a thread that does the LED on/off and a controller thread that periodically changes the blink period. The thread stack size is only 64 bytes and it runs even on an ATtiny.

With all the AVR internal hardware modules (such as SPI, TWI, UART, etc) there is plenty of opportunities for concurrency.

A Scheduler library for the Arduino core is also available. This is a port of the Cosa Threads. Please see github for further details.

Cheers!


Unexplained behavior of char array after using `deserializeJson` I'm using RF24 library to send messages between 2 MCU's : 1) ESP8266 (no Wifi, same code can be compiled to any Arduino board) 2) pro-Micro.
Message is sent in JSON format, while using ArduinoJSON library to serialize and deserialize messages.
Altough entire code works as expected, I get an error in "RFread" function, which _readmsg array loses its content after using deserializeJson.
Attached below  relevant part of "RFread" function. Explanations in code below. Please notice "Mark [X]" in code and Serial output:
char _readmsg[32];                                <---- Storing input in this array
    char t2[32];                                  <---- variable to clone value
    radio.read(&_readmsg, sizeof(_readmsg));      <---- getting RF input and store it in `_readmsg`
    strcpy(t2, _readmsg);                         <---- cloning, part of error seeking

    Serial.print("first: ");                      <---- printing initial value stored. OK. marked [A] in Serial output
    Serial.println(_readmsg);
    Serial.print("duplicate: ");                  <---- printing clone. OK. marked [B] in Serial output
    Serial.println(t2);

    if (key != nullptr)                           <--- check if "msg" key was sent in message
    {
      StaticJsonDocument<80> DOC;
      deserializeJson(DOC, _readmsg);             <---- **error beyond this point**
      Serial.print("second: ");
      Serial.println(_readmsg);                   <---- printing wrong value. marked [C] in Serial output

      if (DOC.containsKey(key))
      {
        const char *outmsg = DOC[key];
        if (out != nullptr)
        {
          strcpy(out, outmsg);
          return true;
        }
      }
      else
      {
        Serial.print("third: ");
        Serial.println(_readmsg);              <---- still error. marked [D] in Serial output
        Serial.print("duplicate2: ");
        Serial.println(t2);                    <---- clone variable is OK. marked [E] in Serial output
        strcpy(out, t2); // if key not present, return entire message
        return 0;
      }

and in Serial port:
message sent OK   <---- irrelevant for debug

15:18:14.934 -> first: {"id":"Port","msg":"fff"}       <----[A]

15:18:14.934 -> duplicate: {"id":"Port","msg":"fff"}   <----[B]

15:18:14.934 -> second: id                             <----[C]

15:18:14.934 -> third: id                              <----[D]

15:18:14.934 -> duplicate2: {"id":"Port","msg":"fff"}  <----[E]

15:18:14.934 -> Error. no such key. got reply: {"id":"Port","msg":"fff"}

Is there a reason for that ? is it a bug ?

When you pass a char* input to deserializeJson(), it alters the input to avoid making useless copies.
This is the "zero-copy" mode of ArduinoJson.
In this mode, the JSON parser modifies the input in-place. The following modifications are performed:

'\0' are inserted at the end of each string
Escaped special characters (like \n) are unescaped

Example:
char[] json = "{\"hello\":\"world\"}";
deserializeJson(doc, json);

After executing the line above, the input variable probably contains something like: "hello\0world\0".
You can find more details in the documentation


Difference between ISR and other functions in AVR twi library I was studying the ISR for twi and I want to know how is it working.

I have two questions about the code handling for ISR and the other functions and what they do exactly:

My first question is about how ISR for twi is working? The following example shows a piece of the ISR for twi library. My concern here is how switch statement is working?

And probably I have to understand how TWSR works; for example, I think when twi module sends or receive an address, the TWSR is updated according to TWSR Status codes. But I really don't understand exactly what is happening?! Which happens first?

The programmer issue the twi operation; like, sending a start address. Then, the TWSR is updated with the code 0x08 which means according to the datasheet "A START condition has been transmitted". If that so, then why in the following ISR code. The status code is called as a switch result for twi operation, then it issue an action based on that??!! that what is confusing to me!
So, is the procedure of twi:
1. Send start address.
2. TWSR is updated with 0x08 as a confirmation for the start action.
3. Here the ISR issues another action based on the TWSR again? This is what I didn't understand.

ISR(TWI_vect)
{
  switch(TW_STATUS){
    // All Master
    case TW_START:     // sent start condition
    case TW_REP_START: // sent repeated start condition
      // copy device address and r/w bit to output register and ack
      TWDR = twi_slarw;
      twi_reply(1);
      break;

My second question is about the relationship between ISR and other functions. For example,

  if (true == twi_inRepStart) {
twi_inRepStart = false;
do {
  TWDR = twi_slarw;
} while(TWCR & _BV(TWWC));
TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE);
}
else
TWCR = _BV(TWINT) | _BV(TWEA) | _BV(TWEN) | _BV(TWIE) | _BV(TWSTA);
while(wait && (TWI_MTX == twi_state)){
continue;
}

Here is another start send address operation. So which one is the real one? The start send in the ISR or this one?

The confusing thing is that there is only one interrupt, and it is called for a number of different reasons.

To make sense of why it's being called you also have to know what you have just done in order to know what to expect. In this case we have just sent a START bit, so we set the current status to "start sent". When the interrupt fires we know that it must be in response to the start bit we sent earlier having been completed, so it's time to then send the address.  It's just implementing a simple state machine.

To answer your second question: both are "real" and used.

When sending data to a slave it can be easily implemented with a non-blocking interrupt arrangement. This makes it fast and efficient, and you can get on with doing other things while the data is being sent. That uses the ISR.

When reading from a slave it's harder to implement it with an ISR and still fit into the Arduino ethos of "data is available immediately", so when using requestFrom a simpler blocking routine is called that doesn't use the ISR. This means that when the function is completed all the data has been received and you can get on with reading it from the buffer. If you used the ISR instead then data wouldn't have arrived until some unknown time after you have made the request - so you would have to implement either some kind of callback system to execute a user function when the data has arrived, or manually block waiting for the data to arrive polling a status set by the ISR, which is pretty pointless anyway. So it's just been implemented as a simple blocking routine.

It's crude, but like much of the Arduino API it "gets the job done with the minimum of fuss" - sacrificing efficiency for simplicity and ease of use.

To break it down for you further:

When using Wire.beginTransmission(...) the ISR is used to empty the buffer onto the physical wires. Your sketch can continue while that is happening.
When using Wire.requestFrom(...) the ISR is not used. Your sketch cannot continue until the whole buffer has been received (or it times out).

When using Wire.beginTransmission(...) you first fill the buffer (32 bytes maximum) with your data to send. Calling Wire.endTransmission(...) then starts the sending of the data from the buffer using the ISR.

When you use Wire.requestFrom(...) a call to the Wire.beginTransmission(...) and Wire.endTransmission(...) functions are called to send the address. This uses the ISR.  Following that the twi_readFrom(...) function is called to receive the data in a blocking fashion. That first blocks itself waiting for the ISR to signal that the I2C bus is available and it has finished sending the address. The twi_readFrom(...) function then, if it's using repeated start, sends the start bit again. If it's not using repeated start then it just gets on with the task of reading the data into the buffer.  The actual reception of the data triggers an interrupt which copies the data into the incoming RX buffer from the FIFO, but that's pretty much all the interrupt does when receiving.

Much of the confusion (and it's confusing even to me) comes because the Wire library is written in two layers - an Arduino API wrapper class which implements the Wire object that you are familiar with, and a pure C set of helper functions which most likely were ported over from some other Atmel application library originally. This makes it quite hard to follow what is going on, since the two programming styles and ways of working are very different. Following the thought processes of two different parties working in different ways with different goals in mind is tricky at best.

To better understand how it all fits together you want to sit down with a couple of example transactions (both read and write) and a copy of the datasheet and trace exactly how the program would flow and respond to the different events and sequences within those transactions. Have the transaction waveforms on paper in front of you and mark on them where the different interrupts trigger. Follow that through in the code and work out what exactly gets called when and why it gets called. Quite an arduous task, but essential if you want to fully understand exactly what is going on in the code.


Can I use my PC or Android mobile as WiFi Shield/Module for Arduino UNO? I'm using an Arduino Uno. Currently I am using an ESP8266 WIFI module to connect to the Wifi. But is it possible to use my laptop or Android mobile as a WiFi Shield/Module? I want to connect with cloud server using the connection.

Thanks in advance.

This problem can be broken into several components:

Communications channel between the Arduino Uno and the laptop or Android mobile

There are several options. The most common and probably easiest is to do serial communication over USB. The Uno has a USB-serial chip that creates a virtual COM port (VCP) on a computer when you connect the Uno to it via the USB receptacle on the board. This VCP is commonly used to upload sketches to the Uno and also to communicate with the Arduino IDE's Serial Monitor.

Another option for communications between your Uno and the laptop or Android mobile is Bluetooth. You can buy a Bluetooth module for your Uno that will allow this. This may be preferable if you need wireless communication.

Application on the Laptop or Android mobile that interprets communication with the Uno

Now you can communicate between the two devices but you need a program running on the Laptop or Android mobile to actually do something with the communication. This application will receive commands from the Uno, and make the desired interactions with the "cloud server", and perhaps respond to the Uno. You will need to have some sort of a command protocol. The details of this will be dependent on which type of communications channel you chose. There are many ways you can accomplish this and the best option will also depend on whether you will be writing this application yourself or trying to find an existing application that suits your needs.

Arduino Uno firmware

This is a sketch you will write and upload to your Uno that sends commands to the laptop or Android mobile via your chosen communications channel and handles any responses.


ESP8266 ISO 8601 string to tm struct I have a web service that returns timestamps in ISO 8601 format, e.g., "2021-06-25T12:00:00"
I'm trying to turn the timestamp string into a tm type struct from the ESP8266 library <time.h>, to perform time calculations using the difftime() function.
I've been referring to the Redhat time functions https://sourceware.org/newlib/libc.html#time, as it seem to be compatible with the ESP library, though all i can find are functions converting tm structs to timestamp strings. Are there any functions to convert a string timestamp into a tm struct and then back into epoch? Or what would be the best way to approach this kind of conversion on the ESP8266 platform?

Try strptime from the time.h.
void setup()
{

  struct tm tm = {0};
  char buf[100];

  // Convert to tm struct
  strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);

  // Can convert to any other format
  strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm);
  Serial.printf("%s", buf);
}

void loop()
{
    yield();
}


How can I have code in a project that won't compile for Arduino? I want to test the algorithms in my code without needing to send it to an actual Arduino board. I figured I could lay out my project like:

project/
    core.cpp      # core algorithms
    core.h        # header for core.cpp
    project.ino   # Arduino setup() loop() calling into core
    pc-main.cpp   # main(argv) calling into core

However, when I do this, the Arduino IDE wants to compile pc-main.cpp, which won't work since it uses stdio and all that. What can I do instead?

Is there a way to hide a file from the build, other than changing the extension which would inconvenience other editors and compilers? Is there a different standard approach to this kind of problem?

What I've thought of:

I could put pc-main.cpp in another directory and have the build for it refer to the files in the Arduino project directory, but that seems awkward and I'd like a more elegant solution.
I could symlink the core.* files into the Arduino project directory from elsewhere, but that would also be inelegant, and inconvenience Windows users should one want to compile the project.
I could put an #ifdef around the contents of pc-main.cpp, but I haven't found a suitable #define to check for, other than board-specific ones.

I don't want a solution which requires extra steps for each build; the whole point of trying to do this is fast and easy development.

I would also prefer one which does not bring in a whole additional build system, testing framework, or IDE; for example, I found arduino_ci and PlatformIO while researching this question. I'll switch to looking at such options if there isn't a good solution to the problem as I've stated it here.

[My question is arguably the same as Project structure to build for PC and Arduino at a high level, but the question and answer there are broad and about organizing modules and not how to make the build actually work.]

I would use conditional compilation, like this:

#ifndef(ARDUINO)
// Non-Arduino code.
#endif


Bot not activating after button press This bot is supposed to begin moving forward when the button is pressed, and stop after counting 3 lines of tape on the ground. Currently it is set up to scan the color of the floor at the beginning and count any major differences as a line of tape. Unfortunately I can't test its tape-sensing capabilities due to not being able to get it to actually start. It will only move if I hold the button down continuously, and stops as soon as I release it. Here is the code and images (It uses the Arduino Pro Mini 3.3v):

#include <SFE_ISL29125.h>
SFE_ISL29125 RGB;
unsigned int master2;
unsigned int detect2;
boolean isOn = false;
unsigned int accumulator = 0;

void setup() {
  RGB.init();
  pinMode(7, INPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  master2 = RGB.readGreen();
}

void loop() {
  if(isOn) {
    if(accumulator < 3) {
      detect2 = RGB.readGreen();
      digitalWrite(8, HIGH);
      digitalWrite(9, LOW);
      if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
        accumulator++;
      }
    } else {
      accumulator = 0;
      isOn = false;
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
    }
  } else if(digitalRead(7) == HIGH) {
    isOn = true;
  } else {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }
}

I strongly suspect the main problems with your code are in these lines:

  if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
    accumulator++;
  }

If I understand correctly, with this code you are attempting to tell whether you have been over a line of tape, which will be indicated by a change in reading from RGB.readGreen(); - say high, low, high.  If so, accumulator++.  (I have no opinion on whether this is a valid way of sensing it, or how well your sensor will work.)

This is definitely broken in one way, and probably broken in another.

First the definitely-broken way:

You want to sense down-up-down-up-down-up (or up-down-up-down-up-down).  Your code senses simply three higher or lower readings.  Your loop() takes no time at all, so when your buggy moves onto the tape, it will immediately read (say) high, then loop round, read high again, loop round and read high again, and again. accumulator is now 3 and we stop the motor.

Second, the maybe-broken way:

What value does master2 have?  Consider that it is an unsigned integer.  You are subtracting 10 from it.  What do you get if its value is 5?  It can'be be -5 because it is unsigned.  How you solve this depends on the possible range of values from RGB.readGreen();.  The implementation looks like it could give a value anywhere in the range, so we have to be careful.

Here's my reworking of your code.  It assumes the concept of checking for values which vary by 10 from the original value is sensible - I've no idea if it is.  (I don't understand what this "middle" values means, but you say you've "already tested the components individually" which I don't believe because your code could never have worked but, assuming you saw something similar working...)  It also makes a very big assumption that the value will change cleanly - from higher to lower exactly once per edge of strip, with no wobbling.  Log out some values to find whether it really does.

#include <SFE_ISL29125.h>
SFE_ISL29125 RGB;
int master2;
boolean isOn = false;
int changes = 0;

#define BUTTON 7
#define MOTOR_A 8
#define MOTOR_B 9

#define LOWER 0
#define HIGHER 1
int last_state = 0;

void setup() {
  RGB.init();
  pinMode(BUTTON, INPUT);
  pinMode(MOTOR_A, OUTPUT);
  pinMode(MOTOR_B, OUTPUT);
  master2 = (int)(RGB.readGreen()/2);
}

void loop() {
  if(isOn) {
    // Wait for 6 changes: up-down or down-up, three times.
    if(changes < 6) {
      int detect2 = (int)(RGB.readGreen()/2);
      digitalWrite(MOTOR_A, HIGH);
      digitalWrite(MOTOR_B, LOW);
      // Count _changes_ in state only
      if(last_state == HIGHER && detect2 <= (master2 - 5) {
        last_state = LOWER;
        changes++;
      } else if (last_state == LOWER && detect2 >= (master2 + 5)) {
        last_state = HIGHER;
        changes++;
      }
    } else {
      accumulator = 0;
      isOn = false;
      digitalWrite(MOTOR_A, LOW);
      digitalWrite(MOTOR_B, LOW);
    }
  } else if(digitalRead(7) == HIGH) {
    isOn = true;
  } else {
    digitalWrite(MOTOR_A, LOW);
    digitalWrite(MOTOR_B, LOW);
  }
}


Wake Arduino (Atmega328) from sleep with ADXL345 interrupt So I'm relatively new to microcontrollers, and I'm having a problem implementing a feature I want for a project.

I've learned about putting an Atmega328P to sleep from this tutorial. I'm using an Arduino Nano, so I only get my current down to ~9mA rather than the µAs the tutor is getting. Nonetheless, it demonstrates the abstraction I want to learn for when I move to just the Atmega328 with no board.

I've learned to wake up my microcontroller from sleep with a falling external interrupt on INT0/D2 from a simple button. My ISR is empty and just boots me back to the loop, which is fine. As an aside, I have heard that it is better to have simple and short ISR's, but I am not completely sure why.

My question is, can I use my ADXL345 to trigger an interrupt that wakes my Arduino? I am semi-familiar with using an ADXL345 over I2C, although I don't understand why my Sparkfun ADXL345 requires different wiring than my unbranded one, but that's for a separate question I suppose.

So my question is, is it possible, and if so, how? Also, is the I2C connection meaningful for an ADXL345 that is primarily being used as a wake-up interrupt on the Z-axis only? (My use case is an item someone picks up, which wakes my embedded circuit out of sleep and begins logging load cell and UWB sensor data, and is put back to sleep after a period of inactivity).

Thanks in advance - I appreciate any and all help!

When using an ADXL345 to trigger an interrupt to wake an Arduino, I2C (or SPI) need not be relevant.  Instead, you can just connect pin 8 or 9 (INT1, INT2) of the ADXL345 directly to the Arduino pin that wakes the Arduino.  Note, INT1 and INT2 in this answer refer to pins 8 and 9 of the ADXL345.

On the ADXL345, map the wake-up event (or events) to whichever of INT1 or INT2 (pin 8 or 9 on the ADXL345) you've connected to the Arduino.  By sending commands from the Arduino to the ADXL345, you can map multiple events to INT1 and INT2 on the ADXL345, and might have both of them connected to different pins on the Arduino for different purposes.

As noted on page 20 of the Analog Devices ADXL345.pdf Rev. E datasheet,

  The default configuration of the interrupt pins is active high. This can be changed to active low by setting the INT_INVERT bit in the
  DATA_FORMAT (Address 0x31) register.

  How do I toggle bits in an ADXL345?

You can use SPI or I2C to set up registers on the ADXL345.  You will need to configure the unit before it does anything, because it powers up into standby mode.  See the second paragraph of POWER SEQUENCING, page 13 in spec sheet, and see Table 6 on that same page:

  At power-up, the device is in standby mode, awaiting a command to enter measurement mode, and all sensor functions are off. After the device is instructed to enter measurement mode, all sensor functions are available.


How to send arduino data to php code I'm new to arduino. I'm doing a project where I need to send a RFID UID to php code. The UID will be detected by the arduino and the rest will happen at the php side. for that I need to get this UID at oho side. I'm using RFID-RC522 and arduino mega 2560. how can I do this?

also I found couple of posts about ethernet. is it the only solution for this? if I use an ethernet shield will it block any ports which I'm using on arduino for connecting the RFID things?

thank you

If you can use Wi-Fi, I suggest you to use ESP8266-01, it's cheap and usefull ! With this chip you can send all data to your server!


Powering via an I/O Line I have an SPI 128x64 OLED display. Is it safe to power this display's VCC from a digital I/O pin? I would like to do this so I can connect it flush to my arduino's header, and so I can control the power going to the display for a "low power" sleep mode.

Thanks for any responses.

Unlikely. An IO pin can only provide 25mA sustained, and 40mA peak. A display is likely to require more than that. However check the datasheet for the display. If by chance it should not need more than 25mA maximum (all pixels white) then yes it may be possible.


HTTP PUT method on NodeMCU I am trying to update values to Firebase. According to Firebase:

curl -X PUT -d '{ "first": "Jack", "last": "Sparrow" }' \
  'https://[PROJECT_ID].firebaseio.com/users/jack/name.json'

We can update using put command. Using curl works fine, but when I look at the header of ESP8266HTTPClient, I don't see any put or patch method there.

I can only see the following:

int GET();
int POST(uint8_t * payload, size_t size);
int POST(String payload);

Whereas in NodeMCU documentation, it is clearly stated it supports the put method too.

http.put(url, headers, body, callback)

http.put() documentation

I cannot find any example.

How can I implement the put method in NodeMCU?

pardon me if i asked too soon. I found the answer.
all verb are supported. but post and get got their own names.

 int httpCode = http.sendRequest("PUT", String(data));

enven post method implement the sendRequest.


Can we detect a magnet using Arduino? If so how? If so, please tell me and also tell me if any interfacing of other microcontroller needed?

I can't comment yet but you probably are looking for a hall effect sensor.

Something like this is a simple version of the sensor. https://www.sparkfun.com/products/9312

You can then do a digitalRead on the DO pin to detect if a magnet is near the sensor.

You would connect the Vdd to 5v arduino supply and GND to the GND of the board.


How to get char array's length I use a LCD display to display a not known size of text ( changes over time ). I wish to display it at the center of LCD ( 2X16 ).

I declare:

  char t[16];
  char h[16];
  sprintf(t, "%.1f%cC %.0f%%", temperature,223, humidity);

Now, since I want to add additional data on a specific line and center it, I need to know it size. When using:

sizeof(t)/(sizeof(t[0])

I get 16 which is the size determined and not its actual size.

How can I get the exact number of chars used?

The function I think you are looking for is strlen - STRing LENgth.

It counts the number of characters in a string up until it finds the "NULL" end of string marker.

Serial.println(strlen(t));