text:
Arduino Ethernet Shield 2: How can I automatically determine the MAC Address?
I'm using an Arduino Mega.
I know that Ethernet Shield 2's come with a sticker with the MAC Address printed on it. This would imply to me that this address is hardcoded into the shield. Is there any way to recover the MAC without manually entering it in the sketch?
Thanks!

No, the W5500 chip does not have a mac address. You can give it any mac address that you want. The router might not like some mac addresses though.
There are online mac address generators.
The sticker with the mac address is an extra service. It is unique number. But it is just a number on a sticker, it is not related to that specific shield.
Often the mac address DEADBEEFFEED was used. But when two different Arduino boards use the same mac address, the router thinks it is the same device. When there are two devices with the same mac address at the same time connected, that is for sure a way to mess up the router.

It would have been so simple to include a little I2C, SPI or 1-Wire EEPROM on there with the MAC address programmed in at the factory.  The price difference would have been negligible.  Such a shame they never bothered...

Thanks for the info. I was afraid of that. Basically, this prototype will eventually go into large-scale production (Using a proprietary board developed from the Arduino code/circuitry, etc. I end up with) so using a randomly-generated mac seems like a bad way to go. Ah well, I'm sure there's an alternative to the Ethernet shield.

This is an old question, but I wanted to share my code which fixes this.
Basically, the next code generates a "locally managed address" and stores it to EEPROM.
On subsequent starts, it read the address from EEPROM so that you would generally get the same IP address from the DHCP server.
If you do not have EEPROM, you may have another memory that survives programming cycles (SPI Flash, RTC RAM, etc) - you'll need to update the sketch for that.
#include <EEPROM.h>

// If defined, report information about MAC ADDRESS INITIALISATION
#define ENABLE_MAC_INIT_MESSAGES

// Local mac address, initialiser can be removed (when using initMacAddress)
uint8_t mac[6] = {0x00,0x01,0x02,0x03,0x04,0x05};

void initMacAddress() {
  // Rather than having a fixed MAC address for an Arduino sketch,
  // this implements a different, random address which is persistant
  // by storing it to EEPROM (which only works when EEPROM is available).

  // Here the MAC ADDRESS IS LOCATED AT ADDRESS 0 OF THE EEPROM
  for(int i=0;i<6;i++) {
    mac[i]=EEPROM[i];
  }

  // Generating a new MAC address if the address found is not locally
  // Administrated.  This test requires that the 2 lower bits of the first
  // byte are equal to "2" (bits 1 and 0).
  // Normally it is only required that bit 1 is "1", but checking bit 0 for a 0
  // allows to detect an uninitialized EEPROM.
  if((mac[0]&0x03)!=2) { // Is this a locally administered address?
    // No a locally managed address, generate random address and store it.
    #ifdef ENABLE_MAC_INIT_MESSAGES
      Serial.println("GENERATE NEW MAC ADDR");
    #endif
    // make sure random numbers used are not always the same
    randomSeed(analogRead(0));
    for(int i=0;i<6;i++) {
      mac[i]=random(256);
      if(i==0) {mac[0]&=0xFC;mac[0]|=0x2;} // Make locally administered address

      EEPROM.update(i,mac[i]);

      #ifdef ENABLE_MAC_INIT_MESSAGES
        if(mac[i]<10) {Serial.print('0');}  // Print two digets
        Serial.print(mac[i],HEX);Serial.print(":");
      #endif
    }
    #ifdef ENABLE_MAC_INIT_MESSAGES
      Serial.println();
    #endif
  }
}

void setup() {
  initMacAddress();
  /*...*/
}

EDIT: An anonymous use suggested a call to randomSeed(analogRead(0)); to ensure that the generated value is random. This (may) need to be done only once in the program.  It's best done in the 'setup()' as  the analog pin that can actually be used depends on the application - one might also use more complex & random initialisation schemes.


text:
Arduino Micro not providing regulated power
I have an arduino micro that works fine off USB. I need to power it from an external 12V power supply. When I connect the 12V supply to the adjacent VIN and GND pins, the arduino will not power up. When I measure the power at VIN, it's 12V. When I measure power at the 5V pin, it's also 12V. If I disconnect the external power and go back to USB, it powers up.
Blown regulator?

Or unconnected ground? Otherwise I can't imagine 12V on 5V without blowing MCU.

In comparing this with another Arduino Micro, it appears that the regulator is malfunctioning.

Is this actually an Arduino product, or some unspecified knock-off?

Actual Arduino. I certainly won't rule out that I fried it at some earlier point, but it's clear that the regulator is not working.

It may blow the entire board. Feeding 12V into the regulated 5V line would likely damage the CPU and various other subsystems.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
MCP23S17 library crashes
I have a rather voluminous sketch with a heap of source and header files.
Now I'm facing the problem, that controlling the MCP23S17 on my board fails in different ways within this sketch. This is rather awkward, because when I modify the sample sketch taken from this library to my needs, the port expander can be accessed and controlled without any problem.
what happens within my own sketch?
If I initialise SPI myself before using any of the library methods, everything of my sketch and hardware but the port expander works flawlessly. I.e. all hardware does what it is intended to, only the pins of the port expander do nothing.
If I remove all SPI commands I inserted there to initialise SPI according to my needs, the code will fail during the first call to MCP23S17::pinMode(…).
Fail means: The CPU crashes. It hangs inside this routine and keepalive-LED stops blinking, serial output is severed. As I don't have any means of debugging besides Serial.print(), I narrowed it down to the call of
_spi->transfer(cmd);

within
void MCP23S17::writeRegister(uint8_t addr)

So something from my other code must interfer with this call, somehow, so the CPU comes to a halt. What the heck do I have to look for?
Additional information:

Portexpander chip select is tied to Pin 7 of Arduino Uno.
Portexpander address i 0
Other device connected to SPI: display
Other notable devices: RTC (on I2C), lot of 1-wire devices.

Addendum
following Majenko's suggestions, I reduced my code to reach functionality in this issue. I did not succeed. So I decided to post two antagonistic sketches, one crashing and one working.
Spoiler: I found my coding flaw myself five minutes ago, I'm going to post it as answer later, but decided to go on writing this addendum as I had intended
Here comes the .ino-file of the failed sketch:
#include <SPI.h>
#include <MCP23S17.h>
#include "spin.h"

void setup() {
    Serial.begin(9600);
    Actors::setup();
    Serial.println("setup finished");
}

void loop() {
    Actors::service();
}

part of this are two further files, from which I removed everything possible:
spin.h:
#ifndef _INC_SPIN
#define _INC_SPIN

#include <MCP23S17.h>

class Actors
{
    private:
    static const uint8_t PexSSPin;
    protected:
    static MCP23S17 portExp;

    public:
    static void setup();
    static void service();

};
#endif

and spin.cpp:
#include "spin.h"

const uint8_t Actors::PexSSPin=7;
MCP23S17 Actors::portExp(&SPI, Actors::PexSSPin, 0);

void Actors::setup()
{
    Serial.print(F("Ac:se#"));
    Serial.print(".");
    portExp.pinMode(2, INPUT);  // not used. INPUT mode prevents damage due to accidental shorting
    Serial.print(".");
    portExp.pinMode(3, INPUT);  // not used. INPUT mode prevents damago due to accidental shorting
    Serial.print(".");

    Serial.print(F("Ac:se!"));
}

void Actors::service()
{
    Serial.print(F("Ac:sv#"));
    Serial.print(F("Ac:sv!"));
}

As noted in my first part of the question this code comes to a halt during the first call to the pinMode() method of the portexpander. There's no serial output after the first pinMode call and the actors weren't working either (when there was useful code left).
On the contrary here comes a working sketch with the same library controlling the same port expander on the same hardware.
#include <MCP23S17.h>
#include <Arduino.h>

#ifdef __PIC32MX__
// chipKIT uses the DSPI library instead of the SPI library as it's better
#include <DSPI.h>
DSPI0 SPI;
#else
// Everytying else uses the SPI library
#include <SPI.h>

#endif

const uint8_t chipSelect = 7;

MCP23S17 Bank1(&SPI, chipSelect, 0);
uint16_t data;

void setup() {
    Serial.begin(9600);
    Bank1.begin();
    Bank1.pinMode(8, OUTPUT);
    Bank1.pinMode(9, OUTPUT);
    Bank1.pinMode(10, OUTPUT);
    Bank1.pinMode(11, OUTPUT);
    Bank1.pinMode(12, OUTPUT);
    Bank1.pinMode(13, OUTPUT);
    Bank1.pinMode(14, OUTPUT);
    Bank1.pinMode(15, OUTPUT);

    // Bank2.pinMode(15, INPUT_PULLUP);
}

void loop() {
    if (data==0)
    {
        data = 0xffff;
    }
    else
    {
        data = 0x0000;
    }
        Bank1.writePort(data);
    delay(2000);
    Serial.println(data);
}

I take it since you're wanting my response it's my library you are using?

Do you have anything connected to pin D10? If so, what, and what mode are you using the pin in?

@Majenko yes your library. pin D10 is connected to the CS of the display. And according to the display library it is used in output mode.

It sounds like some form of conflict, certainly. If _spi->transfer() is hanging then it's most likely that the SPI transaction is never completing, which is something in the SPI library. It may be that your display library is doing things that affect the SPI library in some way.

I would suggest starting with working expander code, then add each extra item until it fails. Then remove everything except the expander and whatever was last added and see if it still fails. If it does then post that code so we can find the conflict.

Ok, I'm going to check that out, by removing everything, first of all all includes to the display library. The library I'm using is DOGM_7036.

I'd love to know, why my question is a bad question...

Since you have answered the question yourself you should accept the answer as the correct answer.

So here is what I found five minutes ago.
I forgot to call MCP23S17::begin()
Simple that is.
Before that, I tried to rule out a whole lot of other things. It never came to my mind, that I could have missed such a vital initalisation.
What did I do to get to this point?

removed every other library using SPI
removed every code using I2C
removed every code using 1wire
removed every code using Interrupts
threw away 9 out of 10 files
removed 9 out of 10 calls for functions which seemed irrelevant for this problem.

None of these measures did anything to solve the problem. Only when I had my code reduced to the minimum, so I could dare to post it here, the single line caught my attention. So this Q&A is not really a technical or coding riddle but more a didactic play on how one can fool himself and what to do to locate errors.
But in the end I only found the culprit by strictly following Majenko's advice to remove everything until the code started to work again.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Suddenly I can't compile any sketch. Not even a blink sketch that I compiled earlier
I use visual Micro for Visual Studio. Out of nowhere, I can't compile for any board. I tried a blink sketch for the nano, and I get intelisense red underlines for simple things like pinMode, digitalWrite, and Serial.print. Here's what I get for an output:
Compiling debug version of 'Nano_Trials' for 'Arduino Nano w/ ATmega328'
Build folder: file:///C:/Users/jf051e/AppData/Local/V.Micro/Arduino/Builds/Nano_Trials/nano_atmega328
Additional Defines: VM_DEBUG;VM_DEBUG_ENABLE 1;VM_DEBUG_BANDWIDTH_THROTTLE_MS 50;VM_DEBUGGER_TYPE_HARDWARESERIAL 0;VM_DEBUGGER_TYPE_SOFTWARESERIAL 1;VM_DEBUGGER_TYPE_FASTSERIAL 2;VM_DEBUGGER_TYPE_USB 3;VM_DEBUGGER_TYPE_TEENSY 4;VM_DEBUGGER_TYPE_UART 5;VM_DEBUGGER_TYPE_USART 6;VM_DEBUGGER_TYPE_USBSERIAL 7;VM_DEBUGGER_TYPE_TTYUART 8;VM_DEBUGGER_TYPE_NET_CONSOLE 9;VM_DEBUGGER_TYPE_Uart 10;VM_DEBUGGER_TYPE_COSA 11;VM_DEBUGGER_TYPE_CDCSerialClass 12;VM_DEBUGGER_TYPE VM_DEBUGGER_TYPE_HARDWARESERIAL;VM_DEBUG_BREAKPAUSE;
Architecture Tools: {runtime.tools.avr-gcc.path}/bin/
Sketchbook: file:\\\C:\Users\jf051e\Documents\Arduino
Sketch Include Paths
Include Path 'C:\Users\jf051e\Documents\Arduino\Nano_Trials'
Core Include Paths
Include Path 'C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino'
Include Path 'C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs'
Library Include Paths (1)
"{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\Nano_Trials.cpp" -o "nul"
The system cannot find the file specified
    Preprocess: "{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\Nano_Trials.cpp" -o "nul"
Unknown error during deep search source code for includes. Attempting alternative regex exploration
System.NullReferenceException: Object reference not set to an instance of an object.
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino._TryRunPreProcessIncludesDiscoveryUntilDone(String sourceFilePath, Board brd, List`1 includePaths, Boolean isTopLevel)
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino.TryRunPreProcessIncludesDiscoveryUntilDone(String sourceFilePath, Board brd, List`1 includePaths, SketchLibraryList knownLibs)
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino._compile(SketchBuilder lsketch, String primaryClassName, Boolean verbose, Boolean isDebug)
Library Include Paths (1)
Build Core Paths: C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino
Using library VM_DBG version 0.0.0 in folder C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG
"{runtime.tools.avr-gcc.path}/bin/avr-g++" -c -g -Os -Wall -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Arduino\libraries" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries" -I"C:\Users\jf051e\Documents\Arduino\libraries" "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG\VM_DBG.cpp" -o "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\VM_DBG\VM_DBG.cpp.o" -DVM_DEBUG -DVM_DEBUG_ENABLE=1 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_USB=3 -DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_UART=5 -DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_COSA=11 -DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -DVM_DEBUG_BREAKPAUSE
The system cannot find the file specified
    Process: "{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -Wall -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Arduino\libraries" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries" -I"C:\Users\jf051e\Documents\Arduino\libraries" "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG\VM_DBG.cpp" -o "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\VM_DBG\VM_DBG.cpp.o" -DVM_DEBUG -DVM_DEBUG_ENABLE=1 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_USB=3 -DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_UART=5 -DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_COSA=11 -DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -DVM_DEBUG_BREAKPAUSE
Error compiling libraries

I swear I didn't touch anything. i was working on a different sketch and when I hit compile, Visual Studio froze and said it was busy. i had to kill the process and try again. I did this like 8 times before i realized that I could do longer compile ANY sketch. I even restarted my PC to no avail. What the heck??

Did your trial period run out?

So I seem to have fixed it. One way or another, I think VisualMicro suffered some type of problem with the installed boards. My first clue was that my sketches still compiled int the native Arduino IDE. So I went into the VisualMicro explorer and noticed that there was an update to 1.6.19 in the board manager (I was running 1.6.13). I don't know exactly what the problem was, but installing the update to 1.6.19 seems to have fixed it.

There are a few suggestions here, here and here:

Ensure you are using the latest Arduino software that is compatible with Visual Micro (this is not necessarily the latest Arduino software!)

Go to Visual Micro menu -> Board pulldown -> Find or install a
board--> Rescan. You should get "Toolchain reload complete". The
Visual Micro forum administrator suggests that you do this twice.

Reset the User's Appdata Arduino folder

Close all IDE's

Delete the C:\Users<USERNAME>\AppData\Local\Arduino15 folder

Start the Arduino IDE once. Close after it has fully started

Then try Visual Micro again

Delete the preferences.txt file (if it exists)
Goto C:\Users<USERNAME>\AppData\Roaming\Arduino and delete the preferences.txt file.

Thanks for the ideas, but none of these worked. I'm still getting errors for basic functions like pinMode(), digitalWrite(), and Serial.print(). It's almost like my standard libraries were corrupted or something.

Hey guys, I seem to have fixed it. I'll edit the post.


text:
Simple Multiple RX/TX SoftwareSerial?
In this project I will be using multiple ESP8266 WiFi modules (4) connected by software serial to an Arduino Leonardo Micro (1 UART). I plan to rotate between all 4 (starting with 2): Open port, write, read response, close port, move on....
This is a very barebones version of my code to address this one issue. Works flawlessly with a single (always open) connection, but it does not work when I close Ser1 (even if I don't start Ser2!!!)
Is the xxxx.end(); command broken or something?
Or am I doing something wrong? :/
Note: This code sends "AT" to the module, it responds with "OK"
When adding Ser2, LED flashes on Arduino periodically indicating it is writing to serial monitor, but nothing appears...
Code:

#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {

  pinMode(10, INPUT);
  pinMode(16, INPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(8, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, OUTPUT);
  Serial.begin(9600);
  //Set up Serial Monitor on host computer

}

void loop()
{

  delay(1000);

  Ser1.begin(9600); // open Ser1

  Ser1.write( 'A' );
  Ser1.write( 'T' );
  Ser1.write( '\r' );
  Ser1.write( '\n' );   // sends the line: "AT" with appropriate format

  Ser1.listen(); // make sure it's listening

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Ser1.end(); //close Ser1 port
  //This breaks the code for some reason....

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.begin(9600); // open Ser2

  Ser2.write( 'A' );
  Ser2.write( 'T' );
  Ser2.write( '\r' );
  Ser2.write( '\n' );

  Ser2.listen();

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }

  Ser2.end();

}

Why are you beginning and ending the object each time instead of just beginning once?

@Ignacio,  Software serial is only capable of one connection at a time, so it must be closed before I switch to a different port. Problem is my attempt to close it breaks the code. :(

No, it is capable of only receiving on one connection at a time.

@IgnacioVazquez-Abrams Do you suggest beginning them all in setup? Then how can I switch the receiving from port to port?

Exactly how you already are.

As Ignacio mentions, you should not be stopping and starting the serial ports. Instead just switch between them with .listen():

Enables the selected software serial port to listen. Only one software serial port can listen at a time; data that arrives for other ports will be discarded. Any data already received is discarded during the call to listen() (unless the given instance is already listening).
SoftwareSerial::listen() Manual Page

So your code would be written as:
#include <SoftwareSerial.h>

SoftwareSerial Ser1(10, 8);
SoftwareSerial Ser2(16, 7);
SoftwareSerial Ser3(14, 4);
SoftwareSerial Ser4(15, 2);
//Set up (RX, TX) pins^

void setup() {
  Serial.begin(9600);
  Ser1.begin(9600); // open Ser1
  Ser2.begin(9600); // open Ser2
}

void loop()
{

  delay(1000);

  Ser1.listen(); // Select Ser1 for receiving
  Ser1.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser1.available() > 0)) { //Read entire string
    Serial.write(Ser1.read()); //Dump it to serial monitor
  }

  //Should Respond with "OK"

  Serial.println(); // Extra line in Serial Monitor for neatness

  Ser2.listen(); // Select Ser2 for receiving
  Ser2.print(F("AT\r\n"));

  delay(1000); // Give it time to send a response or you'll get nothing!

  while ((Ser2.available() > 0)) {
    Serial.write(Ser2.read());
  }
}

I really appreciate how you fixed my problem AND optimised my code at the same time!! I think the main issue was not waiting for a response (I tried your fix lol). Amazing work!!


text:
Wake up Arduino Uno by RTC
I intend to make the device runs about couple hours a day(let say 2hrs) -> go to deep sleep -> wake up in next 7 days -> repeat the process.
I got the code from one of member here (DotPi) which I can able to make the device wake up every 10 seconds and then back to sleep. When it wakes up, the LED is flashing.
My question is how to make the LED flashes for certain amount of time. For example from 7pm to 8 pm. After that the device should go to sleep again and wait for the next alarm triggered.
I was trying to use the while loop for that but the LED always flash and never go back to sleep :(

You are setting the alarm every iteration of your loop. You want to put that in your setup() function.

even I put the "rtc.setAlarm" function in main loop, the device still repeat every 10 second as I expect. My problem is I want to flash the LED for certain amount of time (as the while loop) but the LED is always flashing and never get out of that while loop even the current minute is greater than 30.

Also asked at: http://forum.arduino.cc/index.php?topic=492180

In your while loop, you never check the time again, so when the while loops hits, you will never leave it. You need to request the time again. Something like:
while ( now.minute()>0 && now.minute() < 30)
{
   digitalWrite(ledPin, HIGH);
   delay(100);
   digitalWrite(ledPin, LOW);
   delay(1000);
   now = rtc.now(); // check time again
}

cool, I got what u mean. Silly me :D


text:
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


text:
Serial speed for debugging/logging
I have a sketch where I want to check my nRF24L01's and they work great.
However, due to Serial.print(ln) statements I noticed there is a lot of delay. Is this normal?
I mean, is it better not to user Serial.print at all during speed checks?  (probably not).
What other options would be best? Some I can think off:

Put all debugging info in an array and print it later (downside: more programming needed, probably special logging class)
Print less (bad solution I think, also makes logging more difficult to read)
Use another Arduino (so sending it by other means, via Wire or so? Never tried this, but I think this might be the best solutions.
I couldn't find any print that does not wait until ready sending (which would cause minimal 'downtime' for the running sketch.

I did not try the third option but I think that would be ideal (but cost another Arduino). Since in my project I eventually use multiple AVRs (mostly Arduino's), I was thinking about sending all logging info to one Arduino and let that Arduino print out everything, that means, only one serial monitor, and no delays (or barely) for all others (where it matters).
Do you think this is the best for logging/debugging? Or are there better methods for use with an Arduino?

Option 5: Run Serial at a much higher baud rate. You should be able to go at 1MBaud quite happily.

@Majenko ... With the Arduino IDE I just can chose 250000 baud, should I use a better serial port monitor?

Hell yeah. That thing is ghastly.

I just learned a new word :-) ... going to check for better ones

@Downvoter, can you instead of downvoting all my posts, explain WHY you downvoted, so I may improve the post.

I use a couple of techniques to measure code timing or to instrument it with mimimally disturbing time-critical code:

Run the code-under-test in a loop of N times, taking the difference in the system clock before and after the loop. If the code-under-test is short enough that the loop housekeeping timing might significantly affect the measurement, I'll unroll part of the loop - cut and paste several repetitions of the code-under-test into the loop - to reduce the relative effect.
Toggle an output pin at entry and exit of the code segment-under-test. Measure the pulse width with an oscilloscope, or with a DVM that includes frequency and duty-cycle measurement and calculate the pulse-width from that. I write directly to the I/O port to keep the influence of the software probes (added code) to a minimum.
If I'm trying to collect debugging data without disturbing the code timing, then as you suggest, I store the raw data in an array (raw, to keep it small), dump the raw data in hex to the terminal after the test-run, and expand/interpret it on my PC (to address your point 1., more programming needed). You'll still need some extra programming but it will be in a separate domain (your PC), it can be big, dirty, and slow, and requires less disturbance to your embedded source-code.

Thanks for all those options ... for my test 3 will suffice, 1 I also use indeed for very small timing checks, 2 is also interested, hope my oscilloscope can handle it :-)

(sorry for my late acceptance).


text:
Bluno + PS3 controller?
I'm seeking information about connecting a PS3 controller using Bluetooth to an Arduino.
Bluno cards could be an integrated solution for that, but can it work?
Also, I've seen some tutorials using a USB shield + a Bluetooth dongle: in this case, at some setup steps a USB connection is needed between the PS3 controller and the Arduino. It is still the case with a Bluno card?

While not strictly impossible, using a PS3 controller with the Bluno (ATmega + CC254x) is essentially impractical.
The PS3 controller is either a USB device, or a classic Bluetooth device.

A USB device can only communicate with a USB host.  Neither the ATmega nor the CC254x on the Bluno is capable of being a USB host.  An add-on USB host shield would cost more than simply buying a platform suitable for fulfilling the entire requirement natively.
The CC254x only speaks Bluetooth Low Energy.  It is not compatible with classic Bluetooth devices. To communicate with the PS3 via Bluetooth you would need to add a Bluetooth classic radio to the system.

If you wish to use a PS3 controller you should pick a non-Arduino platform having native USB Host capability or native classic Bluetooth capability.
Otherwise, if you wish to use an Arduino-like platform, pick an earlier generation controller with either a very old wire-per-function interface or a simple synchronous serial interface, for example a PS2 controller.


text:
Arduino 3.3V Conversion
I am fairly new to Arduino. As far I know all official Arduinos run on 5 volts. Or there is Arduino versions that run from 3.3V? I need use Arduino with devices which chipsets all use 3.3V logic level. Do I need modify Arduino to make it  3.3V powered, like described in this Tips, or there is another way? I plan get Arduino UNO R3 ATmega328P board (comes with bootloader for Arduino UNO ZT).

The best solutions to this are to move away from an antiquated ATmega to a modern MCU which achieves full performance on 3.3v.

Nucleo boards (ARM). And on Olimexino 32u4 it's even possible to switch between 3.3V and 5V. So many possibilities

Arduino Pro Mini comes in 3.3v and 5v versions.

Arduino Pro Mini is minimalistic, semi-finished board that comes without pin headers, no on-board USB, and no built-in USB circuitry, so it requires additional components and FTDI TTL Level Serial Converter Cable that should be connected, so the whole construction isn't very handy.

@minto. Soldering things is a basic ability here. FTDI is no-brainer; you need only one. The big plus: minimal footprint. Lately, I don't even solder pins; just solder the wires directly to the board for less hassle and to reduce overall height and fit the Pro Mini in tight spaces.

Soldering is not an issue, but I just preffer standalone device, with all required interfaces already built-in. As it not need to be pocket-size device, the minimal footprint just not required. Additionally, attaching external FTDI basic breakout board isn't convenient.

@minto. Last, but not least, Pro Mini is breadboard friendly. You can put a Pro Mini, an OLED display (1.8") and several led and push buttons on a small breadboard: a whole project in the footprint of an Arduino Uno. The FTDI also comes handy with things like SMS 800 modules.

I correct myself. I was thinking about a 0.98" OLED display

You can use different possibilities:

Use Arduinos which are already 3.3V by default (like Pro Mini, Due if I recall right)
(removed after valid comment of minto below)
Use 5->3.3V adapters, most general devices have adapters which can be bought separately (for under 1$) to convert 5 to 3.3V (including logic level converters)

I think the point 2) "Use the 3.3V pin on e.g. the Arduino Uno" is simply wrong: the Arduino Uno has a 3.3V power source, but the digital I/O pins are based on 5V, not 3.3V. We can't to make the I/O pins 3.3V, unless we are powering the Atmega at 3.3V also.

True, I will remove it from the answer (was mixed up with powering in general)

What about just getting the bare chip so you can run it at whatever rail you want? Seems like the simplest and easiest solution.


text:
Arduino timer ctc mode 4 vs 14
I'm trying to gain an understanding of the Arduino timer and interrupts, particularly the CTC-modes 4 and 12. I wrote a small example in which I generate interrupts while the mainloop sleeps for 1 second and the display how many interrupts occured. It can toggle between mode 4 and 12 with the #if 1.
This works fine for mode 12 ( 50 interrupts/sec ) but in mode 4 it gives -12k interrupts / seconds... unless when I set OCR1A to 39999 again inside the ISR then it does give the expected 50 interrupts/sec, but I'd like to know why.
I think my confusion might be related to not understanding the table-header explaining the modes where it says "Update of OCR1x at". What is meant with that ( who updates it, and to what value? or do I need to update it in the ISR ) ?
Why would OCR1x be updated in mode 12 ( the table seems to state that it is) ? And it seems to work, even if I don't update it...?
Also, the only difference between mode 4 and 12 seems to be the register used for comparing to the timervalue (OCR1A vs ICR1)... but what is so fundamentally different between those? Why are there 2 options and what is the argument to choose for either mode 4 or 12 ?
Update: The issue seems to be related to initialization-order. If OCR1A is set to 39999 at the current location it gets reset to 0 a few lines further. When moving it after TCCR1A = TCCR1B = 0; then OCR1A keeps the value. So it's not necessary to set it on every interrupt.
This also explains why we get -12k counts on mode 4 (because we are comparing OCR1A in that mode, comparing to 0 and generating loads of interrupts)...
Any insight into why the initialization-order matters in this case would be appreciated.
Thanks in advance!

volatile int isr1 = 0;

ISR(TIMER1_COMPA_vect)
{
  // this is called every time our timer-compare matches to ICR1 or OCR1A
  isr1++;

  // when using the #if part below, we need to do this, or we end up with weird values for isr1 ( around -12.000 )
  // If we set it to the original value then we get 50 interrupts per second...
  OCR1A= 39999;
}

void setup() {

  Serial.begin(115200);
  delay(50);

  ICR1 = 39999;                   // 50Hz signal @ 16MHz clock
  OCR1A= 39999;

//TIMSK1 |= 1 << ICIE;            // bit 5: Input Capture Interrupt Enable (execute interrupt when TIFR1.ICF flag is set)
  TIMSK1 |= 1 << OCIE1A;          // bit 4 : Enable the Timer-Output-CompareA-Match Interrupt

  TCCR1A = TCCR1B = 0;            // reset timer-config flags
   // An interrupt can be generated at each time the counter value reaches the TOP value by either using the OCF1A or ICF1 Flag,
   // depending on the actual CTC mode. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value.
#if 1
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with OCR1A, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM12;             // code 4 (CTC, compare with OCR1A, Immediate update of OCR1x, overflow on MAX)
#else
  // Arduino Datasheet 20.12.2. : The counter value (TCNT1) increases until a compare match occurs with ICR1, and then TCNT1 is cleared.
  TCCR1B |= 1<<WGM13 | 1<<WGM12;  // code 12 (CTC, compare with ICR1, Immediate update of OCR1x(?), overflow on MAX)
#endif

  // using a prescaler of 8, which "slows down" the clockticks by factor 8.
  // 1 clocktick takes 0.5 microseconds, so 39999 clockticks need 19999,5 microseconds
  // 1 second = 1.000.000 microseconds, so we get 50 interrupts per second
  TCCR1B |= 1<<CS11;   // timer CS11 = clki/o/8, 1 tick per 0.5 microseconds
}

void loop()
{
  delay(1000);            // wait 1 second
  Serial.println(isr1);   // print how many interrupts we had in that second
  isr1 = 0;               // and reset for the next second.
}

As described in the operation part of the datasheet section, OC1x is double-buffered; the code sets a shadow buffer to a given value and then at some point the hardware copies the shadow buffer to the register that controls operation. "Immediate" means that the buffer is completely transparent since the value is copied immediately.
The difference between modes 4 and 12 is that mode 4 allows the use of ICP1 for input capture and mode 12 allows the use of OC1A for waveform generation.

Thanks you for your reply but it's still not entirely clear to me.
Mode 4 compares to OCR1A, mode 12 to ICR1.
Printing "OCR1A" to serial output every loop, OCR1A is set to 0 ( for both mode 4 and 12), even though it was  initialize to 39999.
That would explain why in mode 4 ( using OCR1A for comparison) it results in -12423. The timer compares with 0 and basically instantly has a hit and triggers the next interrupt, overflowing isr1.
But why/where is OCR1A being set to zero. I can't find a description of that behaviour in the datasheet.

Which device are you using?

An Arduino-Uno (chinese)

So an ATmega328P?

When uploading: "avrdude: Device signature = 0x1e950f (probably m328p)", so yes... ah it also says " AVR Part: ATmega328P"

Well, I don't see anything in the code or datasheet that would explain this, and I can't test the code out myself ATM. It is possible that the MCU is actually a knockoff, but I can't prove that either.

Let us continue this discussion in chat.

Heh, it seems to be related to the initialization order, if we set OCR1A slightly later it's ok.  So I don't need to set it every time in the ISR, but just "later" on init - for whatever reason...  When moving it after TCCR1A = TCCR1B = 0; then OCR1A keeps the value.


text:
How to read a timer's value once stopped?
I've downloaded the Timer1 library but unfortunately it seems that the read() method has been removed from it. I tried also SimpleTimer library from the arduino website but the program didn't compile because of undefined reference to `SimpleTimer::SimpleTimer()' error. Anybody knows how to solve this error or just another timer library which has a read function?
To be more specific I need to start a timer as I press a button and to stop it as it is released.

Have you considered looking for an input capture library instead?

To start a timer, give it a clock by setting the CSn2..0 bits. One set of those bits stops the clock thus the timer. Read the data sheet to be sure.

Here, below is a code which is you looking for. When you pressed a button then a timer is started and when you released it then a timer is stopped. And you can also see that time also means how long button is pressed.
const uint8_t button_pin = 2;

void setup()
{
    pinMode(button_pin, INPUT_PULLUP);
    Serial.begin(9600);
}

void loop()
{
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        push_count++;
        last_press_time = now;
    }

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
            push_count--;
        }
        else {
            Serial.print(F("pushes: "));
            Serial.print(push_count);
            Serial.print(F(", duration: "));
            Serial.print(push_duration);
            Serial.println(F(" ms"));
        }
    }

    last_button_state = button_state;
}


text:
Which component is described as a "jumper" (NOT jumper wire) when working with a motor shield?
In this video I'm watching then instructor talks about using "jumpers". He's got a motor controller shield and at first he says that "during the making of this video we only had 1 jumper, thus only Pin 4 is working", and that as a result he could only move a motor/wheel in 1 direction.
He proceeds to find another jumper, uses it to make Pin 5 work, and then he can reverse polarity and change the direction the the wheel spins.
At first I thought that he must mean header pins, but when he holds the tiny component up, it looks like it's something else:

I read about a "power jumper" on an Adafruit page, but it only applied to one version of the Arduino and sounded like it was to do with Power joining (using the same power source for the motor and controller), so I really don't know if that's the same thing.

It's one of these (or similar). It connects two adjacent male header pins.

Thanks +1, will mark this as the answer. How are they used? I mean why would I want to connect 2 header pins together?

They can be used to form a connection that a user can elect to connect or disconnect as required for an application, or they can be used to choose between multiple mutually exclusive connections, e.g. powering a shield with either 3.3V or 5V sourced from the Arduino.

I mean why would I want to connect 2 header pins together? - it's very commonly done. For example I have a "minimal" board where I sometimes want a power LED to come on, and sometimes not (for measuring low-power consumption). So, I solder on two header pins side by side to make a gap in the circuit to the LED. To make the LED work I just slide on one of the jumper devices that Ignacio showed, and it bridges the gap and completes the circuit.


text:
How to understand the "power economy" of a voltage up-converter (boost converter)?
My online video Arduino instructor makes use of various devices to amplify signals, currents, and voltages. This seems like magic to me.
For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.
I'm going to assume there must be some tradeoff here, because otherwise we can just use a giant string of these up-converters to give the world infinite energy from a single AA battery. I found the Wikipedia articles on this topic a little hard to understand, but basically gathered that if Voltage is boosted then it's at the expense of current. My questions are:

Is my understanding correct (higher voltage = lower current)?
If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?
What are the practical limits of this type of conversion?

I would appreciate a plain-language (easy to understand) answer. I'm also kind of curious how the conversion works, but I assume that will be highly technical.

yes.  2. there's still enough after division. 3. heat, space, economy, added up-front investment, DC-DC power (V*A) loss (~5-20%).

To explain the step up: imagine two batteries in series, the voltage is double the single cell's voltage. now replace the battery with a charged capacitor; same voltage doubling. now imagine you could disconnect the series chain and charge each cap in parallel, using only half the output volts. once charged, re-connect in series and drain. repeat 100,000 times a second and add a smoothing cap to the output to keep a steady double voltage. basically it, though most converters use caps and innductors and more complex cycles...

He is describing a boost converter which steps up voltage at the expense of current. To quote from the Wikipedia page on that subject:

A boost converter (step-up converter) is a DC-to-DC power converter that steps up voltage (while stepping down current) from its input (supply) to its output (load). It is a class of switched-mode power supply (SMPS) containing at least two semiconductors (a diode and a transistor) and at least one energy storage element: a capacitor, inductor, or the two in combination.

As an example, an Arduino Uno consumes around 50 mA from the power jack (at 9V) running a "do nothing" sketch like this:
void setup () {}
void loop () {}

You could say that this is consuming 450 mW of power.
9V * 0.050A = 0.450W

To run from a lower voltage the boost converter (say, 3V) you still need to get 450 mW of power, so therefore it will consume a higher current:
0.450w / 3V = 0.150A

In other words, we now need 150 mA (3 times the current) since we have 1/3 of the voltage.
Also, these converters are not 100% efficient. Say a particular converter is 90% efficient, that means it requires even more current (150mA / 0.9 in this case, being 166 mA).
The efficiency is not linear anyway. It varies somewhat depending on the input voltage and the load. There is a question and answer on Electronics Stack Exchange (Boost Converter Efficiency goes down as Duty Cycle goes up?) which discusses this.

Is my understanding correct (higher voltage = lower current)?

Yes - in the sense that the device consumes power. Thus a higher voltage requires a lower current to deliver the same power. Conversely, if you drop the voltage you need to increase the current to get the same power.

If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?

Yes it matters. You need a certain voltage, with the capability of providing enough current. In this particular case if your batteries can supply 166 mA then the Arduino can still run.

What are the practical limits of this type of conversion?

You will eventually exceed the capacity of your battery to supply enough current. A more elaborate Arduino circuit may involve LEDs and motors. The higher current drain may exceed what the battery can supply, or possibly it will just be drained quickly.
Another factor is that batteries are less efficient when supplying higher current (the quoted mAh figure for a battery is usually for quite a low current). In other words, if you double the current drawn from a battery, the time the battery lasts is not half the time, it is less than half the time. One of the reasons for this is that batteries have an equivalent series resistance (ESR). At higher current drains there is a larger voltage drop over that resistance (some power gets turned into heat, in other words). Thus it isn't practical to try to get 10 amps from an AA battery. The battery will just get very hot.

For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.

This is actually quite inefficient in the first place. The Arduino nominally can run from 5V (if sent directly to the 5V pin on the board) and 4 * 1.2V is 4.8V which should be close enough for practical purposes.
His idea is to step up the 4.8V using a boost converter to 9V (which in itself has some inefficiency) and then use the voltage regulator on the Arduino to drop the 9V back to 5V which is also inefficient because some power is now being dissipated as heat.

Thanks very much. In explanation of the prof's rationale for using the up converter, there was also a motor and motor shield involved, so I assume it used more power. I didn't want to over complicate the question with that detail though.

I presume he has field-tested this concept, so no doubt what he says is right. :) However with motors my comments about the higher current possibly not being available from the battery are even more relevant. Within reason this is a perfectly valid concept. For example, cordless mice which only have a single AA battery in them no doubt have a boost converter inside. You usually find though that mice with two batteries have a longer quoted life (less boosting required).


text:
Tap into display signal
(Newbie Arduino developer).
I am interested to read the signal being sent to a small flat screen display in an industrial appliance, while not disturbing the display. The goal is to capture screenshots and upload them over a network connection.
Is that possible. What do I need to find out about the signal/display?
Any pointers to get started, would be greatly appreciated.

¿What do you mean? Simply read a HIGH/LOW voltage, a current, or you want to be read what char/text/value is displayed? I'm also interested in reading what is displayed in old cell phone (the ones wth physical buttons).

Depends on how much resources (time and money) you have. An AVR based Arduino will have a hardtime capturing display signals and holding and uploading the image. The simples solution is a web-cam.

If you want to interface electronically: Different display technologies (LED and LCD being the most likely of many) combined with many different electronic protocols makes this question too vague to even start to answer. If you want to build an optical interface: To understand patterns captured by a camera, often people use computer vision.  OpenCV is a commonly used software package for computer vision.  However, OpenCV requires a very robust computer to run on.  So only the high end Arduino boards with real operating systems are viable options for this purpose.

On the other hand, if it's a little text-only LCD, being driven not too fast, you might stand a chance as the protocol is fairly simple. More information required certainly.

Will try to see what information can be gathered, when I have it taken apart the next time.


text:
HMC5883L stops reading when x-axis value get to positive value
I've been looking for a solution for this problem for quite a time I tried different I2C libraries; like,

I2C master library using hardware TWI interface
  * Author:   Peter Fleury

But the same problem, I think my problem is in the HMC5883L_my library.
Update: I have to mention that I'm including I2C_TWSR_Check(); function to check the status of the I2C operations success in the HMC5883L library in int16_t data_read (int16_t *results_ptr); function, and as a result I get a successful operations all the time. But, the problem is when the serial monitor of the Arduino IDE is open and I'm watching the values and moving the module with different vectors, as soon as x-axis changes from -ve to +ve values, the serial monitor stops and I have to close it and open it again.
#include <avr/io.h>
#include <Arduino.h>
#include "HMC5883L_my.h"
#include "I2C.h"

int16_t results[3];

void HMC5883L_init (void)
{
  I2C_start(HMC5883L_write);
  I2C_tx(Configuration_Register_A);
  I2C_tx(0x78);
  I2C_tx(0x20);
  I2C_tx(0x00);
  I2C_stop();
}

int16_t data_read (int16_t *results_ptr)
{
  uint16_t lsb,msb;
  int16_t status_of_process = 0;

  I2C_start(HMC5883L_write);
  I2C_TWSR_Check();
  I2C_tx(Data_Output_X_MSB_Register);
  I2C_TWSR_Check();
  I2C_stop();

  I2C_start(HMC5883L_read);
  I2C_TWSR_Check();

  msb = I2C_rx();
  lsb = I2C_rx();
  I2C_TWSR_Check();

  results[0] = msb << 8 | lsb;

  Serial.print("x-axis = ");
  Serial.println(results[0]);

  msb = I2C_rx();
  lsb = I2C_rx();
  I2C_TWSR_Check();

  results[1] = msb << 8 | lsb;

  Serial.print("z-axis = ");
  Serial.println(results[1]);

  msb = I2C_rx();
  lsb = I2C_rx();
  I2C_TWSR_Check();
  results[2] = msb << 8 | lsb;

  Serial.print("y-axis = ");
  Serial.println(results[2]);
  I2C_TWSR_Check();
  I2C_stop();
  Serial.println();
  return status_of_process;
}

void HMC5883L_read_reg (uint8_t reg)
{
  uint8_t reg_dat;
  I2C_start(HMC5883L_write);
  I2C_tx(reg);
  I2C_start(HMC5883L_read);
  reg_dat = I2C_rx();
  I2C_stop();
  Serial.println(reg_dat);
}

As you can see I put I2C_TWSR_Check(); after each I2C operation to see if there's any problem during read operation but I can't see any problem when the module stops reading if x-axis value get to positive region.
This is my I2C library but I don't think there's a serious problem with it because it worked with other I2C modules without any problem.
/*
 * I2C_Library.c
 *
 * Created: 6/6/2017 12:34:39 AM
 * Author : wolfrose
 */

#include <avr/io.h>
#include <Arduino.h>
#include "I2C.h"

void I2C_init(void)
{
    //set SCL to 100kHz
    TWSR = 0x00;
    TWBR = 0x48;
    //enable TWI
    TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
    while (!(TWCR & (1<<TWINT)));
    TWDR = address;
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
    while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void)
{
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
    TWDR = data;
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
    while (!(TWCR & (1<<TWINT)));
}

uint8_t I2C_rx(void)
{
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
    while (!(TWCR & (1<<TWINT)));
    return TWDR;
}

void I2C_TWSR_Check(void)
{
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch(Status)
  {
    /////////////// MASTER TRANSMITTER //////////////
    case 0x08:
    Serial.println("Start is OK");
     break;
    case 0x10:
    Serial.println("Re start");
     break;
    case 0x18:
    Serial.println("SLA+W OK ACK");
     break;
    case 0x20:
    Serial.println("SLA+W no ACK");
     break;
    case 0x28:
    Serial.println("data TX OK ACK");
     break;
    case 0x30:
    Serial.println("data TX OK no ACK");
     break;
    case 0x38:        // arbitration lost in SLA+W or data TX
    Serial.println("arbitration lost in SLA+W or data TX");
     break;

    /////////////// MASTER RECEIVER //////////////
    case 0x40:
    Serial.println("SLA+R OK ACK");
     break;
    case 0x48:
    Serial.println("SLA+R OK NO ACK");
     break;
    case 0x50:
    Serial.println("data RX OK ACK");
     break;
    case 0x58:
    Serial.println("data RX OK NO ACK");
     break;

     default:
     Serial.println("Error");
    break;
  }
}

Have you seen this: http://hackaday.com/2017/07/29/everything-you-need-to-know-about-logic-probes/

are any of the error messages being displayed?

I don't see where the 'wait for ack/nak' on transmit nor where the 'send ack/nak' after receive is being handled.  Is that handled in the hardware?  if not, it needs to be handled in the code.

@Jot No I haven't, I'm downloading the video right now it should be interesting I'm thinking now of how powerful logic analyzers to detect errors, as with my current configuration for debugging I'm applying Arduino IDE and the serial monitor should be enough to know what is going on but actually I couldn't detect the problem.

@user3629249 No, everything looks working properly but as soon as x-axis value gets to positive it stops reading and I have to close the serial monitor and open it again to enable reading again.

@user3629249 >> 2nd comment, no in software it's 'I2C_TWSR_Check();', it's in the I2C library.

The function: I2C_TWSR_Check() does NOT wait for the ACK/NAK nor does it send that byte.  Infact the function checks the status register to see if a proper response from the slave was received, when bytes were sent.  After thinking it over, I suspect the hardware is handling the ACK/NAK communication

since your calling the I2C_TWSR_Check() function after each communication is complete, you should be seeing the output from this: Serial.println("SLA+R OK ACK"); all the time there is a successful receive communication and the output from this: Serial.println("data TX OK ACK"); all the time there is a successful transmit communication.  Your question does not mention this output.  please apply an EDIT to update

Suggest printing the whole status register before checking the bits, so you/we know what the actual status is, including when the X axis transitions from negative to positive

why is the posted code sending start and stop for each byte when sending/receiving a multibyte value.  The normal way that I2C works (after establishing communication) is the master sends start, command, stop.  then the slave sends ack then if the command was to send data then the slave sends start, data ... data, stop.  then the master sends ACK.  A very similar sequence is used when the master wants to send data.

@user3629249 First of all, thank you so much for the replies and the help. Secondly, for your first concern about ACK/NAK, well the I2C_TWSR_Check() function checks if the ACK/NAK for data or address is received or not that what I think is the process for checking ACK/NAK. But I think you mean something else, well I'm thinking of while (!(TWCR & (1<<TWINT))); where this bit is responsible for each I2C operation completion, could this bit is what you mean? Because I don't know anything about handling ACK/NAK by software or hardware.

Suggest printing the whole status register before checking the bits, so you/we know what the actual status is, including when the X axis transitions from negative to positive, I don't understand what you mean exactly, the status register is linked with the specified values for each I2C master values in the 328p datasheet, anything else is considered as an error in the last function in the I2C library.

@user3629249 why is the posted code sending start and stop for each byte when sending/receiving a multibyte value ... rest of comment, I know that, I'm actually not applying a stop function after each byte send/receive, if you see the void HMC5883L_init (void), it sends multiple bytes because one member told me that i can do it in two ways, whether to send a stop after each byte of send multiple ones with one stop. See https://arduino.stackexchange.com/questions/39373/hmc5883l-not-working-in-continuous-mode/39383#39383

Suggest reading/understanding the I2C bus specification.  Here is a link I2C

I think I'm working pretty well in my I2C library, because I applied Peter Fleury's I2C library as I mentioned in the main topic and the same problem happened. I think my problem is in the HMC5883L library.

I'm working now with a new strategy, which to apply twi main library.


text:
Arduino Pro Micro not recognised by computer or showing up in ports
Around 4 days ago my Arduino Pro Micro arrived. I've been messing around with it, using it to run keyboard commands on a computer. Just recently, whenever I plug it in to the computer it isn't detected by ports or anything. The green light is still on, and the left red light (looking at it from the side of the micro USB input) still works as well, however the right red light no longer works. Can someone tell me what's happening? Have I broken it all ready?

What was the last sketch you uploaded to it?

The arduino pro micro is notoriously difficult to program. I am sure you have figured this out when first installing the drivers but on power up, the micro runs a bootloader for <750ms  so for me at least, it was extremely difficult to install drivers.
However, if you look at this guide by sparkfun, you will see that resetting the board in quick succession will load a longer 8 sec bootloader, which gives your more time to program it. Obviously, this is not normally something you need to worry about as the Arduino IDE automatically resets the board sending it into the bootloader when you upload a sketch to it.
Back to your problem, if it is not popping up as a device when you plug it in to your computer, go into control panel > system > hardware > device manager and look to see if you can find it there. If it still doesn't show up, do what I said above and reset it twice and hopefully you will see the bootloader appear where you can reinstall the drivers for it. You can find the appropriate drivers in the same location where you installed the IDE originally.
Hope this helps!

Sorry to tack onto a 4yr old thread, but hoping this helps others, as it would have me.
Unbeknownst to me,some USB micro cables are power-only and don't have the data lines. I had one of these in my rotation of cables, and while the LEDs lit up nicely, the USB does not appear. I was sure it was not a cable prob as I thought I'd tried multiples. I was unaware I had one of these power only USB cables about - marked with the USB Trident just like the others.
So if you have the 'dead USB' problem with your Pro Micro, do make the effort to be absolutely sure of your cable situation.
I read the debugging posts across the web far and wide, but I yada-yada'd the cable check, as I never saw anyone point out the cable might be undamaged, but just a null-data variant.  My bad obvs - but just FYI for others like me.


text:
How do I connect a LED strip to a Multiwii SE 2.5?
https://www.m.nu/neopixel/mini-skinny-neopixel-digital-rgb-led-strip-60-led-m-black-pcb-1m
I just purchased this led-strip that I plan to use with my Multiwii SE 2.5.

I power the Multiwii itself via a power distribution board where I connect a 3s LiPo battery. Now I wonder how I would wire my LED strip in order to use it with my Multiwii. I have a few smaller LiPo batteries if I need to power the LED itself (not via the 3s LiPo that powers the Multiwii) but the best solution would of course be to power them together.
I appreciate all help I can get.

Have you looked at any NeoPixel libraries yet?

yes the adafruit one. it works with arduino and since the multiwii is arduino-based i am positive it can be used with the multiwii also? i am just a bit confused on the schematic

Which part? It only needs one pin.

this is my first project so sry if i dont follow along 100 %. if i udnerstand correctly 1 pin goes to a open D-pin. but how does the led get battery? if i look at this image https://www.google.se/search?q=arduino+led+strip&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiUlcC3v7HVAhWE1xQKHQxxBYQQ_AUICigB&biw=1920&bih=983&dpr=1#imgrc=KxTVn-hmlWKCjM: it seems to get volt from the arduino itself. How do i make sure the multiwii powers the led-strip with the 3s lipo?

The 3S LiPo will burn out the strip since it only takes 5V as the specs say. So connect it to 5V.

The led strips I've used with my Naze32 have three connection, +5VDC, GND and DATA. I'm not familiar with your FC but based on the image you provided it looks like you would use one of the two I2C ports. As long as you don't try to run too many LEDs (I've maxed out my FC with 32 LEDs no problem) the +5VDC connection should be able to power the LEDs. Obviously connect LED GND to the FC GND. You'll need to check the docs for you FC to confirm but it would make the most sense to me to connect the FC SDA to the LED DATA. The FC SCL would not be used.
NOTE: If your PDB has a +5VDC output you'd be better off using that one to power the LEDs.
In the picture with the Arduino one of the leads is providing +5VDC. I've read the suggestion for LED strips to place a capacitor across the +5VDC and GND to make it more stable but I don't and I've not had any issues. FYI, the lead to the Arduino is for GND and DATA (being driven by one of the Arduino Digital I/O Pins.


text:
Weird behaviour of rotary encoder values
The plan is to control a NEMA 17 stepper motor with an endless rotary encoder.
First, I found a code to read the rotary encoders data on www.HowToMechatronics.com by Dejan Nedelkovski. It basically manipulates an integer and outputs it on the Serial Monitor.
Works almost perfectly except that it actually doubles the count of steps the rotary encoder does.
So a clockwise turn subtracts 1, outputs it in the SM, subtracts 1 and outputs it in the SM again. Same in the other direction with adding 1. Although being not a big deal for intended use of the rotary encoder data, I think this has something to do with the problem.
In the code down below you will find a modified version of the code from Mr. Nedelkovski. I added a few lines to move the motor a few steps in each direction.
Clockwise rotation works as I expected.
One step on the rotary equals subtract, output, movement, subtract, output, movement.
But counterclockwise rotation now adds 1 to the rotary position and subtracts it immediately, leaving the motor in moving back and forward.
But if I move the rotary very very slowly it will work.
Why are the rotary values jumping around once I added the lines?
Is there a way to solve this?
The code:
/*     Arduino Rotary Encoder Tutorial
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 *  to make it work with a stepper
 *  modified by me
 *
 */

#include <Stepper.h>

#define outputA 52
#define outputB 50

int counter = 0;
int dir = 0;
int aState;
int aLastState;

Stepper myStepper(200, 47, 49, 51, 53);

void setup() {

  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);

  Serial.begin (9600);
  // Reads the initial state of the outputA
  aLastState = digitalRead(outputA);

  // set the speed at 60 rpm:
  myStepper.setSpeed(60);

}

void loop() {

  aState = digitalRead(outputA); // Reads the "current" state of the outputA
  // If the previous and the current state of the outputA are different, that means a Pulse has occured

  if (aState != aLastState){
    // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise

    if (digitalRead(outputB) != aState) {

      counter ++;
      myStepper.step(50);

    } else {

      counter --;
      myStepper.step(-50);

    }

    Serial.print("Position: ");
    Serial.println(counter);
  }

  aLastState = aState; // Updates the previous state of the outputA with the current state
}

Thanks for taking your time to read this and help me. I hope that a detailed explanation will help solving the problem.

most rotary handler only fire on the leading or trailing edge, you fire on both...

@dandavis Does it mean that the encoder is broken?

no, it means you need to check not just that the gpios are different, but that they are 0 (or 1) and have changed, but not the other. something like if (digitalRead(outputB) != aState && aState==1)

Unfortunately, I couldn't find the issue.
BUT I used another approach which worked fine.
I used the ClickEncoder library.
This time, my rotary encoder triggered 4 events per notch.
After a little research I found out, that it's possible to set the steps per notch with this library.
I used this code to initiate the ClickEncoder:
encoder = new ClickEncoder(A15, A14, A13, 4);

The first three arguments define the pins the encoder is connected to. The last argument sets the steps per notch. Now it works like a charm!
Full code:
#include <ClickEncoder.h>
#include <TimerOne.h>

ClickEncoder *encoder;
int16_t last, value;

void timerIsr() {
  encoder->service();
}

void setup() {
  Serial.begin(9600);
  encoder = new ClickEncoder(A15, A14, A13, 4);

  Timer1.initialize(1000);
  Timer1.attachInterrupt(timerIsr);

  last = -1;
}

void loop() {
  value += encoder->getValue();

  if (value != last) {
    last = value;
    Serial.print("Encoder Value: ");
    Serial.println(value);
  }

  ClickEncoder::Button b = encoder->getButton();
  if (b != ClickEncoder::Open) {
    Serial.print("Button: ");
    #define VERBOSECASE(label) case label: Serial.println(#label); break;
    switch (b) {
      VERBOSECASE(ClickEncoder::Pressed);
      VERBOSECASE(ClickEncoder::Held)
      VERBOSECASE(ClickEncoder::Released)
      VERBOSECASE(ClickEncoder::Clicked)
      case ClickEncoder::DoubleClicked:
          Serial.println("ClickEncoder::DoubleClicked");
          encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
          Serial.print("  Acceleration is ");
          Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
        break;
    }
  }
}


text:
Can an Arduino be used to read data from a serial port?
People often use Arduinos to send data over serial to other peripherals (flashing firmware onto modules, etc) by pulling RES to ground,  connecting the TX and RX pins to the device being programmed, and then sending data to the Arduino over serial. As an alternative, one could also remove the ATmega instead of grounding RES.
That being said, there should be no reason why one could not receive data from a connected device in the same way. However, no matter what I try, I never succeed in using an Arduino to relay serial input from another device over USB.
I have even tried setting up a simple echo to no avail (even though the TX and RX LEDs flash):
Is it even possible?

When you program a device in the way you suggest data is already flowing in both directions. That is why you have to connect both TX and RX to the other device. There must be something fundamentally wrong with your setup for your loopback test to fail.

@Majenko I am using Arduino's own serial monitor and have an Arduino Nano/Uno (tried both) connected to my computer, with the RESET pin being pulled to ground, and TX connected to RX. Sound alright?

@Majenko I have also tried this with another laptop, and different serial monitors (picocom, minicom and screen)

Well, I just replicated the circuit you show above and used minicom and it worked perfectly.

Mine is a genuine Arduino Uno. Is yours?

@Majenko Yep. Strangely, when I connect another Arduino that is outputting something to serial, I can get this to work.. But the loopback still doesn't work...

Yes, it can, and the wiring diagram you have drawn works perfectly for me using minicom in Ubuntu.
The majority of serial communication is bi-directional anyway - especially when using it to program a device.
There is absolutely no difference between interfacing the built-in USB->UART adaptor to an external device of your choice and interfacing it with the ATMega328P chip. Just because the ATMega328P chip is on the same board doesn't make it in any way special - it is just a UART interfaced device.
If your setup is not working you can try:

Physically remove the ATMega328P chip to see if that is interfering even when held in reset
Check for software that may be interfering with your communication, such as the notorious ModemManager.

I have tried removing the ATMega from the Uno, and also tried using a Windows laptop. That being said, however, you have answered my question, so I will accept this as an answer. Troubleshooting my issue seems off topic for this site.

Maybe your wires are not working right.

Hmm, the wires work fine when the serial in is coming from another Arduino (running a sketch)


text:
Pointer problems using Adafruit MotorController
This may be a very simple problem but it has had me going round and round in circles, it is VERY similar to this [ Problem with wrapping Adafruit Motor Controller function calls in a class] question but try as I might I couldn't resolve the issue using this example. So I will include my code and hope that someone with more experience takes pity on me.
This code compiles with no errors but the motors don't start Like the linked question it all worked before it was separated into the individual files.
robot.ino:
#include "E:\chhs2017\LegoRobotics\SketchesThatNeedToWork\RobotBase\RobotBase.h"

RobotBase *base;

void setup(){
    base = new RobotBase();
}

void loop(){
    base->moveRobotForward(base->HALF_SPEED);
//  base->stopRobotAfter(1500);
}

RobotBase.h:
#ifndef ROBOTBASE_H
#define ROBOTBASE_H

#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

class RobotBase{

    public:
        const int MAX_SPEED = 255;
        const int THREE_QUARTER_SPEED = 190;
        const int HALF_SPEED = 127;
        const int QUARTER_SPEED = 90;
        const int MIN_SPEED = 30;

        RobotBase();

        void moveRobotForward(int inSpeed);
        void moveRobotBackward(int inSpeed);
        void moveRobotLeft(int inSpeed);
        void moveRobotRight(int inSpeed);
        void rotateRobotRight(int inSpeed);
        void rotateRobotLeft(int inSpeed);
        void stopRobotAfter(int time);

    protected:
        Adafruit_MotorShield AFMS;
        Adafruit_DCMotor *myMotorM1;
        Adafruit_DCMotor *myMotorM2;
        Adafruit_DCMotor *myMotorM3;
        Adafruit_DCMotor *myMotorM4;
};
#endif

RobotBase.ino:
/*************************************************************
* this is the robot base control class which is designed for a
* four wheel robot construction using an Adafruit_DCMotor controller
* and and arduino Uno
**************************************************************/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
#include "E:/chhs2017/LegoRobotics/SketchesThatNeedToWork/RobotBase/RobotBase.h"

RobotBase::RobotBase()  {
    AFMS = Adafruit_MotorShield();
    myMotorM1 = AFMS.getMotor(1);
    myMotorM2 = AFMS.getMotor(2);
    myMotorM3 = AFMS.getMotor(3);
    myMotorM4 = AFMS.getMotor(4);
}

void RobotBase::stopRobotAfter(int time){
    delay(time);
    myMotorM1->run(RELEASE);
    myMotorM2->run(RELEASE);
    myMotorM3->run(RELEASE);
    myMotorM4->run(RELEASE);
}

void RobotBase::moveRobotForward(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

void RobotBase::moveRobotBackward(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::moveRobotLeft(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::moveRobotRight(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

void RobotBase::rotateRobotRight(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::rotateRobotLeft(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

Thanks in Advance!

You've not actually said what the problem is.  You've said "Its similar to this...", but it isn't because you have initialised the pointer.  Its strange that you have a RobotBase.ino rather than RobotBase.cpp, but if it compiles that must be OK.  You might want to check the values returned by AFMS.getMotor() to make sure they aren't NULL

Sorry if i didn't make it clear the problem is the motors don't spin, everything compiles without error but motors don't go. I also thought about the ino vs cpp but didn't have time to test it today

Silly question, are you supplying enough power?

12v dedicated to the motors which comes in via the power input of the motorshield

I was hoping you would say I'm running it of D3 :)

Nah these are 12v motors to move a 1.5-2kg robot around petty quickly! Four of them might be a little sluggish running off D3 :-P

Hey Guy's As I suspected it was actually an easy fix after leaving it alone for a couple of days came back with fresh eyes and saw the problem straight away. I had failed to start the MotorController board. So all that was needed was the begin function call base->AFMS.begin(); in the setup of robot.ino, all working fine now.
Thanks again for your help.

It may be the way you are initializing the motor shield object.
Try doing:
RobotBase::RobotBase() : AFMS() {
     myMotorM1 = AFMS.getMotor(1);
     myMotorM2 = AFMS.getMotor(2);
     myMotorM3 = AFMS.getMotor(3);
     myMotorM4 = AFMS.getMotor(4);
}

I can't test this solution yet as the hardware is at work but could you explain the reasoning behind the idea? Is addind the AFMS () after the call to the constructor extending AFMS? wouldn't i need to define that in the class definition in the .h file first?

AFMS is an instance of Adafruit_MotorShield and is defined in the header already. All this is doing is initializing it as part of the constructor of RobotBase.

AFMS = Adafruit_MotorShield(); takes an instance of Adafruit_MotorShield initialised by the default constructor and copies it to your variable AFMS.  :AFMS(){ Initialises your variable AFMS using the default constructor for Adafruit_MotorShield.  Its a subtle difference, but not copying things is always a good plan.       Do you need to change AFMS? No, because AFMS() is calling the class's default constructor.  You could do int aNumber(0); if you wanted, but you do int aNumber = 0; they are the same.

You could go a step further and do : AFMS(), myMotorM1(AFMS.getMotor(1)), myMotorM2(AFMS.getMotor(2)), myMotorM3(AFMS.getMotor(3)), myMotorM5(AFMS.getMotor(4)) {}  I think that will work, you might get issues with ordering, because of the dependencies on AFMS.

Both ideas were tested nothing to note occurred, so I am going to revert the code back to the previous layout. I understand your comment on efficiency and not making unnecessary copies of libraries, But as I am using this code with young (year 9; 14-15yr olds) students I need to consider readability as well as efficiency. To explain bringing Adafruit_MotorShield object to our code and use some of its features is easier if we actually bring the object to our code- I'll work on upping the efficiency later (when I get my head around it) :-D

Any other Ideas on where my stumbling block is?


text:
LinkNode D1 Serial stops working when using pinMode
The following code works. I get an output in the console every second of "Hello" and then the analogValue of the photoresistor.
int greenLedPin = D1;
int yellowLedPin = D2;
int redLedPin = D3;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  Serial.begin(9600);
//  pinMode(greenLedPin, OUTPUT);
//  pinMode(yellowLedPin, OUTPUT);
//  pinMode(redLedPin, OUTPUT);
}

void loop() {
  analogValue = analogRead(lightSensorPin);
  Serial.println("Hello.");
  Serial.println(analogValue);
  delay(1000);
//  digitalWrite(greenLedPin, HIGH);
//  digitalWrite(yellowLedPin, HIGH);
//  digitalWrite(redLedPin, HIGH);
}

Now as soon as I uncomment the pinMode commands nothing shows up on the console.
int greenLedPin = D1;
int yellowLedPin = D2;
int redLedPin = D3;

int lightSensorPin = A0;
int analogValue = 0;

void setup() {
  Serial.begin(9600);
  pinMode(greenLedPin, OUTPUT);
  pinMode(yellowLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
}

void loop() {
  analogValue = analogRead(lightSensorPin);
  Serial.println("Hello.");
  Serial.println(analogValue);
  delay(1000);
//  digitalWrite(greenLedPin, HIGH);
//  digitalWrite(yellowLedPin, HIGH);
//  digitalWrite(redLedPin, HIGH);
}

Any idea what might be going on?

Does it happen when only one of the Dn pins is uncommented?  (I'm thinking the definition of Dn might be to the wrong GPIO pin)  - I'll test you code when I get home to see if I get the same result.

Move int greenLedPin = D1; and int redLedPin = D3; to another pin, because D1 and D3 is Tx and Rx.

http://esp8266.github.io/Arduino/versions/2.0.0/doc/reference.html

Would plugging things into the D1 and D3 pins like LEDs cause this sort of weirdness to happen? My problem eventually became the chip completely ignoring any changes in my sketch. Editing the sketch or even uploading a completely different sketch resulted in the chip simply running the same old code every time.

FYI here is an image of the LinkNode D1: https://m.media-amazon.com/images/S/aplus-seller-content-images-us-east-1/ATVPDKIKX0DER/A2TOL213PF2CAG/B01DD641G6/pdmYH3IESLKD.UX970_TTW_.png
D1 is marked as "TX->D1" and D2 is "D2" and D3 is "D15/SCL/D3", so D3 isn't RX0

https://s3.amazonaws.com/linksprite/Linknode+D1/LinkNode-D1-sch.pdf
Shows pin 15, 16 (D1, D3) is connected to the USB/Serial IC.
And YES, the old code interrupts the upload of the new code. A solution is to press the reset button before the Arduino IDE shows "Upload code", this will put the ESP-12 into programming mode.

I actually did hit the reset button right after compiling but before the IDE showed Upload Code. Same result.

Sorry the correct procedure is: Connect LinkNode D1 to your PC. Press and hold the Reset button, and then Connect D8 (Flash) to ground (GND). Release the Reset button, and then disconnect D8 from ground. And now its in programming mode.


text:
Sensor for turning rail direction
I am trying to control an actuator carrying a carriage made from stepper motor. My problem is that after the carriage reach certain height, I want it to delay for several minutes and change direction to move the other way around.
Any suggestion on what sensor to use? I tried to use EndStop switch like the one in 3D printer but I haven't found any luck as it simply cuts the electronic connections once the carriage hits it.

Sounds like it depends on your mechanical setup, but how about a microswitch? Or a hall-effect sensor?

If you are using a microprocessor, specifically an Arduino, then what you need to do is send the signal from the 'switch' (as defined by Mark Smith) into a digital input port and then let the Arduino make the electronics pause before reversing.  From you post it sounds like (and I am probably wrong) you have put the switch in between the power source and the actuator.

(Diagram by Majenko)

I usually use draw.io for my block diagrams. Gives much more professional looking results with less effort ;) Like this: http://majenko.co.uk/resources/Stuff.png

@Majenko - Shhh.. don't tell anyone but I'm at work and was limited to Word.  :)  I'll check it out, thanks.

It's a website. No need to be "limited" these days ;)

Thank you!! I just tried it last night with 'switch' and it works beautifully


text:
can someone please fix this code
there is something wrong with this code logic and i can't put my hand on it so if any one can fix i would really appreciate it
Basically the code is used to receive couple of char from Bluetooth or serial monitor combine them together in an array then print this array then search for ":" in this array and atoi them into two different integer
IE (50:90) will be (50) and (90) in two different integer that are then used to control the direction and the speed of a motor
//motor a
int enA = 9;
int in1 = 8;
int in2 = 7;

//motor b
int in3 = 5;
int in4 = 4;
int enB = 3;
char data[32]; // Allocate some space for the string
char inChar; // Where to store the character read
byte index = 0; // Index into array; where to store the character

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(enA , OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
  pinMode(enB, OUTPUT);
  Serial.println("\n String conversion testing");
}

void loop() {

if(index < 31) // One less than the size of the array
      {for( int i = 0; i < sizeof(data);  ++i )
          data[i] = (char)0;

          inChar = Serial.read(); // Read a character

          data[index] = inChar; // Store it
          index++; // Increment where to write next
          for( int i = 0; i < sizeof(data);  ++i )
          Serial.println (data);

      }
    char* command = strchr (data, ":");
    if (command !=0)
    {
      *command = 0;
      int direc = atoi (data);
      ++command;
      int speeds = atoi (command);
      Serial.println(speeds);
      Serial.println(direc);
     int s;
     s = map(speeds, 0, 100, 0, 255);
    if (direc >= 85 &&direc <=100 ){//odam
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
    }

      else if (direc >=260 && direc <=280){  //reverse
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
      }

     else if (direc >=350 && direc <=360 | direc <=10 && direc >=0){ // RIGHT
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
     }

      else if (direc >=170 && direc <=190){ // LEFT
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
      }

      else if (direc >=120 && direc <=150){ //FORWARD LEFT
        digitalWrite(in1,LOW);
        digitalWrite(in2,HIGH);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
      }

      else if (direc >=30 && direc <=60){ // FORWARD RIGHT
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,HIGH);
        analogWrite(enB,s);
      }

     else if (direc >=210 && direc <=259){ // BACKWARD LEFT
        digitalWrite(in1,HIGH);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
     }

     else if (direc >=300 && direc <=340){ // BACKWARD RIGHT
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,s);
        digitalWrite(in3,HIGH);
        digitalWrite(in4,LOW);
        analogWrite(enB,s);
     }

      else{ //If bluetooth module receives any value not listed above, both motors turn off
        digitalWrite(in1,LOW);
        digitalWrite(in2,LOW);
        analogWrite(enA,0);
        digitalWrite(in3,LOW);
        digitalWrite(in4,LOW);
        analogWrite(enB,0);
      }
    }
  }

@user35247 - Please don't literally "fix" the code by editing the question. Post an answer instead.

      inChar = Serial.read(); // Read a character

      data[index] = inChar; // Store it

The above is almost certainly not going to work as expected. You need to check if there is serial data available before reading it. (ie. call Serial.available()).
I have a page about reading from serial that might help you with that.
For example, your loop might look like this:
void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

Notice that the Serial.read is only done if Serial.available is true?

what about this part of the code though
inline char* command = strchr (data, ":");       if (command !=0)     {       *command = 0;       int direc = atoi (data);       ++command;       int speeds = atoi (command);       Serial.println(speeds);       Serial.println(direc);

What about it? You need to fix what I mentioned first, and probably add a debugging display to show what sort of string is being passed to that piece of code.


text:
LM35 readings are erratic
My son just did the Love-o-meter project in the Arduino Start Kit. However, the sensor readings of the LM35 temperature control vary widely. Below is a sample. What could be wrong?
Sensor Value: 217, Volts: 1.06, degrees C: 105.96
Sensor Value: 587, Volts: 2.87, degrees C: 286.62
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 320, Volts: 1.56, degrees C: 156.25
Sensor Value: 445, Volts: 2.17, degrees C: 217.29
Sensor Value: 141, Volts: 0.69, degrees C: 68.85
Sensor Value: 510, Volts: 2.49, degrees C: 249.02
Sensor Value: 247, Volts: 1.21, degrees C: 120.61
Sensor Value: 168, Volts: 0.82, degrees C: 82.03
Sensor Value: 595, Volts: 2.91, degrees C: 290.53
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 206, Volts: 1.01, degrees C: 100.59
Sensor Value: 606, Volts: 2.96, degrees C: 295.90
Sensor Value: 125, Volts: 0.61, degrees C: 61.04
Sensor Value: 290, Volts: 1.42, degrees C: 141.60
Sensor Value: 487, Volts: 2.38, degrees C: 237.79

Here's the code:
const int sensorPin = A0;
const float baselineTemp = 25.0;

void setup(){
  Serial.begin(9600); // open a serial port
  for(int pinNumber = 2; pinNumber<5; pinNumber++){
    pinMode(pinNumber,OUTPUT);
    digitalWrite(pinNumber, LOW);
  }
}

void loop(){
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor Value: ");
  Serial.print(sensorVal);
  // convert the ADC reading to voltage
  float voltage = (sensorVal/1024.0) * 5.0;
  Serial.print(", Volts: ");
  Serial.print(voltage);
  Serial.print(", degrees C: ");
  // convert the voltage to temperature in degrees
  float temperature = (voltage) * 100;
  Serial.println(temperature);

  if(temperature < baselineTemp){
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+2 &&
    temperature < baselineTemp+4){
    digitalWrite(1, HIGH);
    digitalWrite(2, LOW);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+4 &&
    temperature < baselineTemp+6){
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(3, LOW);
  }else if(temperature >= baselineTemp+6){
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
  }
  delay(1);
}

The GND is connected to the left most connector in the LM35, the A0 to the middle, and the power to the right most connector.

Maybe you mistyped the code? Didn't wire correctly? We need more information.

Either the person can't decide if they are in love or not, there is a problem with the power supply (is it a battery?), there is some dodgy wiring, you are reading the values too fast or there is a bad earth.  Is it possible to post your code and a photo of your setup?

A link to this project would help, or copy and paste the code.

Point 1 - Don't use D0 and D1 (the first two), because they are the Rx and Tx ports for the serial line, at best the it won't work.

I moved it to D3 to D5, but the sensor values are still the same, i.e. they vary wildly.

Looking at http://www.ti.com/lit/ds/symlink/lm35.pdf (page 3, LP package) and the way the sensor is facing in the picture, the pinout is 5V, Signal, GND, but you switched 5V and GND? (in this case of reverse polarity you have probably burned out your sensor already.)

I've had a look round and spotted this:
https://electronics.stackexchange.com/questions/117970/why-is-my-analog-temp-sensors-signal-so-unstable
In summary it says that the fault maybe that the Arduino's 5V isn't stable enough, so you need to decouple it.  For once it seems that running from batteries may have been a better idea.
I've also seen posts saying there should be a 500Ohm resistor between the Ground of the LM35 and Ground.  Apparently it says 499Ohm on the datasheet.
And as a final resort I saw said that the 'Data Direction Register' influenced the analog pins.  If it was set to digital output this could lead to unstable readings for the ADC.  Basically it implied you needed to set the analog pin's to pinMode (A0, output). But I really don't think this will work


text:
Preprocessing problem
I've a little problem, I'm trying to create a library with processor variables for tune it.
So in .ino I declared my preprocessor var, but preprocessor variables appear not defined in my library. (Notice that I've create a folder test/test.h in libraries directory of Arduino IDE)
Some code to reproduce the problem :
test.ino :
#define TEST

#include "test.h"

void setup() {}
void loop() {}

test.h (edited, reverse error message, this is solution)
#if defined(TEST)
  #error "DEFINED"
#else
  #error "NOT DEFINED"
#endif

If I compile it, I fall on #error "NOT DEFINED".
Somebody with an idea ?
Have a good day

What you are doing should work IMO, have you tried #define TEST (1) ?

Note that using #defines in your sketch will have no effect at all on any usage of those defines in source code (.c and .cpp files), or the header file included in said source code files, in your library. It will only affect the single instance of the header file that is included in your sketch. Using #define in your sketch to configure a library is seldom does what you actually intend it to when you set out.

You should understand the concept of the Translation Unit to get a better insight into why #define in the sketch won't affect your library's source code operation.

The code is working properly. You have mixed up your error messages. The code should be:

#if defined(TEST)
  #error "DEFINED"
#else
  #error "NOT DEFINED"
#endif

UPDATE: The question was edited after the time of this answer to correct the mixed up error messages.

Please, start by reading the Writing a Library for Arduino Tutorial. That will solve your question.