text:
How to send Multiple decoded IR signals in one script
My final goal is to use my Arduino microcontroller as an "automatic remote". For now I would like to know how to send decoded NEC protocols one after another in a script.
I am using the Nano V 3.0 with a IR led I salvaged from an old remote. I used a VS838 and a 338R IR receiving module to decode the signals, both work 100%
I know how to send one protocol in a loop.
e.g
#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

I also know how to send the same protocol repetitively.
(Although it won't work in the loop I reckon it'll work in the final script)
e.g
#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0xFFFFFFFF, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

However, I would like to include 106722DD, 10676897 ,10678877 and send them in one single C++ Script.
I was thinking something like calling each script through a loop might suffice but I have no idea how to do it in C++
Any help will be appreciated.

I'm not 100% certain what you are asking, so sorry if there is superfluous info in here.
Given that:
void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

Sends a single command twice as one burst I think what you want to do is this:
void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(106722DD, 32);
        delay(40);
        irsend.sendNEC(10676897, 32);
        delay(40);
        irsend.sendNEC(10678877, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

If that works it could be generalised into:
// New function to send 'items' codes which are held in the array 'data'
void sendMulti (const uint8_t& items, const uint32_t* data)
{
    for (int i = 0; i < 2; i++)
    {
        for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex)
        {
            irsend.sendNEC(data[itemIndex], 32);
            delay(40);
        }
    }
    delay(5000); //5 second delay between each signal burst
}

void loop () {
    static const uint8_t MaxItems = 3;
    uint32_t  data[MaxItems] = {106722DD, 10676897, 10678877};

    sendMulti(MaxItems, data);
}

Then you could move onto reading the codes from serial or a network, etc.

Thanks it's working so far i'll post some updates as i progress.


text:
Arduino and Raspberry Pi - initiate I2C communication as slave
I would like to interconnect Raspberry Pi and Arduino over I2C.
RPi will act as MASTER while Arduino is SLAVE.
I understand that I2C is designed that only master can send messages to slaves and then wait for responses.
I have sensor connected to Arduino, Arduino check periodically sensor value. My intent is, when sensor value exceed defined limit, inform RPi - send message to it. I want RPi as MASTER, because it also can query Arduino anytime. Can I start communication as SLAVE device?
Is it possible somehow? Do I need to use different bus than I2C?

See answer below.  With pigpio, the Pi does not have to be a master, and  you can have ore than one on the same I2C bus.

You need to use a separate signalling method to alert the Pi that a sensor value is ready to be collected.
This is usually done using an interrupt signal. Your Arduino changes the state of a GPIO pin which is connected to a GPIO pin (through suitable logic level translation as necessary) on the Pi. When the Pi sees that pin change state it requests the data from the Arduino.
It is most common to have the transition from HIGH to LOW as an interrupt signal (aka Active Low) since that allows a simple wired-OR arrangement (open drain GPIOs with a pullup resistor) to allow more than one device to raise the same interrupt.

Yes you can!
The new pigpio library allows the Pi to act as a slave so all devices are equal.
Before this recent release, the Pi was always a master and had to poll the others, interrupting them.
But now you can let the other devices work on their own time schedules without the interrupts.
Here is where you get it

source: Stack Exchange

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

authors: อดิพงษ์ ทองอยู่

sort: votes


text:
Lcd display shield, no characters
So, I've been trying to make an Lcd display shield I got from ebay to work with arduino. Using this very simple code:
#include <LiquidCrystal.h>

#define RSPin 8
#define EnablePin 9
#define DS4 4
#define DS5 5
#define DS6 6
#define DS7 7

#define LCDColumns 16
#define LCDRows 2

LiquidCrystal lcd(RSPin, EnablePin,DS4,DS5,DS6,DS7);

void setup()
{
  lcd.begin(LCDColumns, LCDRows); //Configure the LCD
  lcd.setCursor(0,0);
  lcd.print("Hello, World!");
}

void loop()
{

}

Actually I've tried several simple examples, checked pins physically to make sure I'm using the right order, But no luck. backlight is on, no characters at all. Am I missing something? Or should just contact the seller to send another shield.

My guess: wrong contrast settings (on blue potentiometer)

I've tried rotate it, doesnt seems to do anything

So, after some close inspection I noticed that the blue potentiometer wasnt soldered in correctly. Also, its needs to be turned quiet a lot to have some effect. Might replace it completely. But now it works!

Usually, PCB based potentiometers require many turns (~25) to cover the full range.  If a pot has been used a lot, a poor soldering joint will indeed come loose.  A super poor soldering joint comes loose without any help from the pot.

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


text:
How do I write the codes in #define in an IR Receiver circuit?
So I'm trying to turn an ON LED OFF or an OFF LED ON using a TV Remote. In the #define line, I write the hex code received from pressing the designated button on the TV remote. However, during compilation, an error saying unable to find numeric literal operator 'operator""DE74847' appears. I've scoured the web and can't come up with a solution.
#include <IRremote.h>
#include <IRremoteInt.h>
int ledPin = 13;
int IRPin = 3;

#define code1 0575

IRrecv irrecv(IRPin);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn();
  pinMode(ledPin, OUTPUT);
}
void loop()
{
  if (irrecv.decode(&results))
  {
  unsigned int value = results.value;
  int ledState  = digitalRead(ledPin);
  switch(value)
  {
    case code1:
    if (ledState = HIGH)
    {
      digitalWrite(ledPin, LOW);
    }
    else
    {
      digitalWrite(ledPin, HIGH);
    }
    break;
  }
  }
  else
  {
    digitalWrite (ledPin, LOW);
  }
   unsigned int value = results.value;
  Serial.println(value);
    irrecv.resume();
}

Here's the code. Please help.

Could you add in the full error you receive, please?

Try putting the #define line before the #include lines.  If the define is being used in the included files they wont see it as it is now.

From the error you give, I can't see why you'd think the problem is with the define. It also seems like the code you've provided is different from the code that gave the error.

Check the error line number. It might be that you have entered characters that are not allowed in a literal number.

You have to prefix HEX numbers with 0x so the compiler knows it's HEX. 0575 is an octal number, not a HEX number. DE74847 is a random string of characters that it can't understand. Use 0xDE74847 instead.

Your problem is that you don't know how to form hexadecimal numbers.
In your code (in future, if you have an error in the code please post the code that is causing the error, not something else entirely - it makes it nigh on impossible for people without my psychic abilities to answer your question) you have defined a macro containing what you think is a hexadecimal number. In fact it's just a random string of characters and the compiler doesn't know what to make of it:
#define code1 DE74847

So in your switch construct, when code1 gets replaced with the content of the macro, you end up with:
switch (value) {
    case DE74847:
        ....

The compiler has no idea what a DE74847 is.
Numbers other than decimal numbers (0-9 and the decimal point) are identified by the use of a prefix:

0b... is binary
0 is octal (in your completely different code you have the number 0575, which is actually octal, and represents the decimal value 381)
0x is hexadecimal.

So adding 0x to the start of your hexadecimal value will tell the compiler to treat it as hexadecimal:
#define code1 0xDE74847


text:
Previous and updated releases of Arduino IDE are not be able to start on Win 8.1 x64
I have tried to install many versions of IDE, but non of them has started successfully. There is just the logo of the program shows up and then nothing happens.
My laptop: Toshiba Satellite C50-A630
The releases I have installed: 1.6.12 , 1.6.13, 1.0.6

Which Java Version you got installed?

Delete your preferences.txt file.

I had the same problem with various IDE versions. Deleting the preferences.txt solved the problem for me.


text:
How does an 8bit MCU make use of data-types over 8bits?
how does an 8bit MCU handle 16bit output?
How does an 8bit MCU store values higher than 8bits?
I am using an attiny, on an adafruit trinket. and other 8bit MCUs.
http://www.atmel.com/devices/attiny85.aspx
I was doing some things with uint32_t datatypes, when it hit me, that it would seem like uint32_t would be an incompatible datatype. Even 2Byte data type like int seems peculiar. "int stores a 16-bit (2-byte) value"
considering the MCU is 8bit.
I saw this link, that sounded like it would have more info, but its pages are incomplete. http://playground.arduino.cc/Code/DatatypePractices
So how does that work?
How does an 8bit MCU make use of data-types over 8bits?

Human children are often first taught to do arithmetic with single-digit arguments, and then to do operations on multi-digit place-value numbers using rules that give a sequence of single-digit operations.  Computers use very similar methods, doing multiple word-width operations to accomplish wider ones.

It's the compiler that convert the 32-bit operations into 8-bit instructions.

Is MCU micro controller unit?

The basic answer is that the processor does math in 8-bit chunks, so it takes more instructions than it would on a 32-bit processor.
A good answer is found in EE.SE

Actually a 1-bit MCU could be used to execute code (e.g. C/C++) with N-bit numbers. Not very fast as it will require O(N) operations for addition and subtraction.
To better understand this for the 8-bit AVR MCU used in Arduino I recommend reading the Instruction Set Description Manual, AVR/GCC Wiki and assembler code listings for some sketches. This will reveal the secret(s) behind this "alien technology/magic".
Cheers!


text:
RF signal boosting
I'm working on a quadcopter project. The quadcopter will be quite autonomous, but sometimes I'll need to send some messages to it. So I built a simple, one-way RF communication system based on two simple 433 MHz modules.
It works, but when the propellers of the quadcopter approach the take-off speed it begins having trouble in receiving the RF messages, and after a certain speed it stops working.
I suppose this is due to the electrical noise produced by the four little brushed motors. Yesterday I increased a little the transmitter's voltage, and that increased a little the minimum antenna-antenna distance with the motors on, but that is far from enough.
What else could I do to increase the transmitter's power?
Thanks in advance
Noè
P.S.: Here are my RF modules:

You might like to read my investigation into those modules (https://hackingmajenkoblog.wordpress.com/2016/11/18/cheap-433mhz-transmitters/) and then rethink using them - instead using something more reliable.

You can add an antenna to the ANT hole. Just add some copper wire. You'd have to experiment with the length of it, to get the best range.

thanks Majenko, I read your investigation. My modules are better built than yours and my rf system is very simple (I only need to send a few dozen of bits per second (and not every second), without any transmission sopeed requirement, andalways in the same direction), but of coure you're right, they're worth 99p. I will change them, but I can't get them in the next few weeks, so for the moment I would like to improve the existing system...

You need something like LoRa modules. I have attached very nice 1/4 wave antennas with radials to these modules, and they still couldn't receive well... Polarity even became an issue. Got 25 meters without obstructions, but the slightest obstruction (leaves even) cut the signal off. Look into LoRa. I will now read @Majenko's blog.

No one uses those for micro aircraft, as 2.4 GHz solutions are both more reliable and lighter weight.  But the minute your quadcopter makes it off the ground, you'll probably discover that you don't have a working flight stabilization firmware.  Spend some time on rcgroups where people who have actually done this (mostly in reflashing cheap toys with custom firmware) discuss the issues.

As has been mentioned adding an antenna to the "ANT" pin on the transmitter will help. You need to get the length right though, but it's easy to calculate.
Best is to use single-core insulated wire (0.6mm is a good choice).
To calculate the right length you first need to know your frequency. Then you convert that to the wavelength, and then cut your wire to a quarter of that length.
Wavelength is c/f where c is the speed of light (in m/s), and f is the frequency.
So for 433MHz you have a wavelength of (299792458/433000000) 0.69m.
A quarter of that is 0.173m (17.3cm), so cut your wire to that and solder it on.
For 315MHz the wavelength is (299,792,458/315000000) 0.95m, so an antenna length of 0.238m or 23.8cm.
This is known (unsurprisingly) as a quarter wavelength antenna and is the most efficient length for a simple wire antenna.
Whether it will be strong enough to penetrate the noise from the motors is anyone's guess.
You can also add small capacitors (0.1µF ceramic) across the terminals of the motor and between the terminals and the body, to absorb some of the EMI which may help to allow more signal through - as shown here.

Tanks again, @Majenko. I already have an antenna, but it's like twice the length you wrote here; i'll cut it. But I just read the post mentioned by Gerben (here): the author says that I sould subtract the coil soldered in the module (I have a coil which is in fact the first part of the external antenna) to this lenght, does this make sense? And what about other types of antenna? Is it possible to connect some kind of more efficient antenna to such a simple rf module?

It is always possible to attach other antennas, yes. A Yagi array (TV antenna) will increase gain at the cost of omnidirection. You should be tackling the motor noise first though. Don't try to overpower it, eliminate it.

But the antenna port requires desoldering the coil. What range and punchiness did you get with your modules? Partnumbers/link?

I have been using RF modules for different projects that involves using motors. And I have never experienced something like that. Since the motors a significant quantity of current to take off, I recommend using another power supply for the electronic part of the drone and use the actual battery just for the motors.

I can't add a second battery (the quadcopter needs to be very lightweight), but the electronic power supply is protected from the electrical noise of the motors. I think the problem is the electromagnetical noise: if it is too strong the rf signal is "hidden" in the noise and the receiver can't detect it... (is that correct?)


text:
Custom ISR triggering function/value
Is there a way to write a custom function which would be the mode/reason to trigger an interrupt. I have an analog joystick connected to my arduino analog pin. It reads a value of 689 on one end and 0 on the other and around 480 in the center. I would like to trigger an interrupt based on these value changes i.e an interrupt when it  more then 600 and another when less then 10. None of the pre-defined modes RISING,HIGH,LOW,FALLING,CHANGE are working satisfactorily.

No. Interrupts are hardware. You cannot "create" interrupts in software.
The closes there is to what you are after is the Analog Comparator (see section 27 of the datasheet).
The analog comparator allows you to trigger an interrupt if a voltage is above (or below) a reference voltage which is up to you to provide.
For anything more complex you would need to use external comparators to trigger on different voltage levels which then trigger external INT pins on the ATMega.

Of course, you can make software interrupts on Arduino; it just costs a hardware pin. The following is a quote from the Atmel ATmega48A/PA/88A/PA/168A/PA/328/P datasheet:
"13. External Interrupts
The External Interrupts are triggered by the INT0 and INT1 pins or any of the PCINT23...0 pins. Observe that, if enabled, the interrupts will trigger even if the INT0 and INT1 or PCINT23...0 pins are configured as outputs. This feature provides a way of generating a software interrupt."
You set up an interrupt on the pin you select for the purpose, you set the pin as output, and then you trig your "software interrupt" by writing a value to the pin.

This could be combined with @Edgar Bonet's suggestion to use a free-running ADC, which generates an interrupt every 104us. The ADC interrupt does a range check and, on entering or leaving the range, raise a PCINT to carry out whatever actions are required.

As Majenko already said, you cannot do that. But you can look for
alternative ways of achieving a similar end result. The real question
is: what are you trying to achieve? Interrupts may not be the best
answer.
I assume what you have in mind is a program roughly along these lines:
// Interrut handler called when input > 600.
void handleHigh()
{
    // ...
}

// Interrut handler called when input < 10.
void handleLow()
{
    // ...
}

void setup()
{
    // Register the interrupt handlers.
    attachInterrupt(ANALOG0, handleHigh, MORE_THAN_600);
    attachInterrupt(ANALOG0, handleLow, LESS_THAN_10);
}

void loop()
{
    doSomeStuff();
}

Of course, that syntax for calling attachInterrupt() does not work, I
just made it up.
The most obvious alternative is to read the value through an analog
input in loop() and act accordingly:
void loop()
{
    // Check the analog input.
    int sample = analogRead(A0);
    if (sample > 600) handleHigh();
    if (sample < 10) handleLow();

    // Do the rest of the job.
    doSomeStuff();
}

No need to use interrupts. The only drawback is that the latency of your
response to a change in the joystick position can be as long as the time
your program takes to run through loop(). This should normally not be
a problem: the joystick is a very slow mechanical device, and your loop
should take no more than a few milliseconds. If the loop if really too
slow, you are probably doing something wrong, like using delay(). You
should then fix that problem rather than trying to work around it with
interrupts.
Just for completeness, there is an interrupt-based solution. Assuming
you have no other analog input to read, you could configure the ADC to
continously read the same input (say, A0) in the so called “free
running mode”, and trigger an interrupt on each reading. In the ISR, you
can then call one of your interrupt handlers if needed (if the sample you
get is outside [10, 600]). Here is how you can do it on an Arduino
Uno:
void setup()
{
    // Configure the ADC in "free running mode".
    ADMUX  = _BV(REFS0)  // ref = AVCC
           | 0;          // input channel = A0
    ADCSRB = 0;          // free running mode
    ADCSRA = _BV(ADEN)   // enable
           | _BV(ADSC)   // start conversion
           | _BV(ADATE)  // auto trigger enable
           | _BV(ADIF)   // clear interrupt flag
           | _BV(ADIE)   // interrupt enable
           | 7;          // prescaler = 128
}

// ADC interrupt service routine.
// Called each time a conversion result is available.
ISR(ADC_vect)
{
    // Read the ADC.
    int sample = ADC;

    // Call the handlers if needed.
    if (sample > 600) handleHigh();
    if (sample < 10) handleLow();
}

Edit: With the code above, the ISR runs every 104 µs. Then you
should make sure that your handlers take significantly less than that
time to complete. Otherwise they will consume 100% of the CPU power
whenever the joystick is in the range to trigger one of them. As a small
optimization, you could declare the handlers static inline in order to
avoid the overhead of a function call.

Thank you Edgar. I cannot use the loop to check the value since I have other code running there but this input has higher priority. But I guess the second suggestion would work. Thank you

@Vignesh: You wrote: “I cannot use the loop to check the value since I have other code running there”. This makes no sense at all. See the doSomeStuff() call in my example: it's still there when you check the input in the loop.


text:
Which library to choose? <Wire.h> or "Wire.h"?
I know that in C++, to include a library, you either put the library name in <x> or "x". Now, I believe that this was because of a major change in the C++ language a some time ago.
Now, in Arduino, there are 2 types of Wire (I2C) library : <Wire.h> and "Wire.h".
Which one is the right one?
I've seem people using both, and they both seem to work.

The proper distinction is exactly what paths are searched for the include files.
<...> searches the "system" paths, while "..." searches both the system an "local" paths.
From the GCC manual:

-I dir
Add the directory dir to the list of directories to be searched for header files.  Directories named by -I are searched before the standard system include directories. If the directory dir is a standard system include directory, the option is ignored to ensure that the default search order for system directories and the special treatment of system headers are not defeated .  If dir begins with =, then the = will be replaced by the sysroot prefix; see --sysroot and -isysroot.
-iquote dir
Search dir only for header files requested with #include "file"; they are not searched for #include <file>, before all directories specified by -I and before the standard system directories.  If dir begins with =, then the = will be replaced by the sysroot prefix; see --sysroot and -isysroot.

Note that the Arduino IDE only uses -I, so there is little to no distinction between <...> and "...".
Commonly the main usage of the distinction is to use <...> to include system or library headers, and "..." to include headers that are part of the actual sketch / application, since the "current directory" is automatically added as a local include path.

So both "Wire.h" and <Wire.h> would work?

Yep. I commonly see both being used, though I for one only ever use <Wire.h>.

Specifically, "file.h" searches the directory containing the current file first. Thus, "file.h" would work for both, finding your local version of file.h before searching the library. However I write "file.h" or <file.h> to explicitly specify - to the reader - which one I mean to include. See [this page describing the gnu compiler's "include" syntax]{https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html)

http://en.cppreference.com/w/cpp/preprocessor/include
#include <filename>

The intent of this syntax is to search for the files under control of the implementation. Typical implementations search only standard include directories. The standard C++ library and the standard C library are implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options.

#include "filename"

The intent of this syntax is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides and, only if the file is not found, search the standard include directories as with (1).

So basically it's intent is to give some idea of where the file should be.
I, myself use "" for files that are inside the directory of my program. And <> for files or libraries that are in my path or other external locations.

This question is also more related to programming in general as Arduino specific.
Also see:
https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename


text:
Why can't my .cpp file have a class of the same name?
I made a new Arduino IDE project ABC, and am given ABC.ino. Then I create a XYZ.h and XYZ.cpp.

ABC.ino:
#include "XYZ.h"

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

XYZ.h:
#ifndef XYZ
#define XYZ

#include "Arduino.h"

class XYZ { };

#endif

XYZ.cpp:
#include "Arduino.h"
#include "XYZ.h"

When I try to compile this, I get some error:
In file included from sketch/XYZ.cpp:2:0:
XYZ:8: error: abstract declarator '<anonymous class>' used as declaration
 };
 ^
exit status 1
abstract declarator '<anonymous class>' used as declaration

However, when I rename my class to something other than the file name, like XYZa, the compilation succeeds.

Why can't I have the same name class as the file?
I've done C++ projects (independent of Arduino) via Xcode and nano, and this has never been a problem.

INCLUDE THE FULL CODE!!!

@DatHa -- This is the full code. It's extremely boilerplate. :)

#define XYZ
...
class XYZ { };

After preprocessing, what do you think that ends up as?

IDK. But, if you're suggesting that it's because it's an empty class, I think I've ruled it out. If you add void QRS() to .h and void XYZ::QRS() {} to .cpp I still get that error AND another one.

Do you know what #define XYZ actually does?

I think it (along with #ifndef and #endif) is suppose to keep from duplicate code during linking?

That is what it is being used for. I asked if you know what it does?

Not particularly. :)

Ok. If I tell you that #define defines a symbol (XYZ in your example) as whatever follows it (nothing at all in your example) then you may see what is happening?

Ahh!!! Yes. I always assumed #define ends at a return carriage. After adjusting the first 2 lines by appending _H_, it begins to work. So, that leads to me asking, why does it work now?

Because now you are defining XYZ_H_ as nothing, and leaving XYZ as XYZ.  When you use #define, any occurrance of the symbol you have defined gets replaced verbatim with what you defined it as (nothing in this case), so by using XYZ  you ended up with XYZ being replaced by nothing, so the class definition ended up as class  { };

#define XYZ

class XYZ { };

The first line tells the "C preprocessor" (called before C and C++ compilers) to replace XYZ with nothing everywhere it happens, hence after preprocessing, and before compiling, that code becomes:
#define XYZ

class  { };

This is where C++ compiler complains. It has nothing to do with your file name.
Among C and C++ programmers, it is commonly admitted that header files should be protected by macros named after the file name including the extension:
#ifndef XYZ_H
#define XYZ_H

If you use this practice, you won't have this problem anymore.

That's what is inconsistent with my Arduino program and my other ones (Xcode/nano). I forgot to append the _H_ (or _H as you prefer).


text:
How come `MyClass.MyStaticMethod()` doesn't work, but `Serial.begin()` does?
MyProject.ino:
#include "MyClass.h"

void setup()
{
  Serial.begin(9600);
  // MyClass.MyStaticMethod();
  MyClass::MyStaticMethod();
}

Both uncommented lines work, but the commented (when uncommented, of course) results in this error: expected unqualified-id before '.' token.
Now, I know this is because of the incorrect scope-resolution. Yet, how come Serial manages to call static functions without the need to use :: to correction to scope-resolution.
How come MyClass.MyStaticMethod() doesn't work, but Serial.begin() does?

. is used to call a method on a class instance whereas :: is used to call a static method within a class itself.
There is no Serial class - Serial is merely an instance of the HardwareSerial class.
#if defined(UBRRH) && defined(UBRRL)
  HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
  HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

If you want to use . then you have to instantiate your class and not use a static method:
class MyClass {
    static void myStaticMethod() {
    }
    void myMethod() {
    }
};

MyClass Fred;

// ...

Fred.myMethod();
MyClass::myStaticMethod();

Ah. That was quite the misnomer since instances are usually with a lower case. I thought it was a class. :)

That is the normal way, yes - but since when have Arduino done things normally? ;)

If a newcomer (myself) is just beginning to see abnormalities, I can't imagine how many you've found. :)


text:
Bootloader on Atmega328p overwrites whenever it gets programmed
I built my first custom circuit board with an Atmel ATMega328p-AU the tqfp-32 form factor. I connected xtal1 and xtal2 to an external 16mhz crystal to 22pf caps tied to ground. It seems to work great, I load the Arduino Bootloader using AVRDude and an arduino as an isp. As soon as I load a sketch on using the ftdi it blows out the bootloader and I can't upload a new sketch until reloading the bootloader. The sketch works as expected, my board has an on board relay and an onboard mosfet I've programmed various blink patterns on both the mosfet and relay.I just don't want to have to reload the bootloader everytime I want to make a change, my sketch is an evolving piece of work and it's frustratinf to take these steps. So far I've tried changing the lock bits to 0x0F 0xEF 0xFF and 0X2F. I've tried various fuse bits, I've changed the signature 0x1e 0x95 0x14 to 0x1e 0x95 0x0F. Nothing seems to change the results, the only thing I've managed to do is one upload caused the chip to run at 8mhz instead of 16mhz, oops. That was easily fixed though. Please if someone can help that would be great, unfortunately the fuse bit calculators I have found don't have the 16mhz crystal as an option even though it's clearly functional.
In Summary
Sketches overwrite my bootloader and I want my bootloader locked but I can't find a solution after nearly a full day of googling and experimenting

... probably should also have pin 6 of the ATmega328p connected to Vcc as well, but probably doesn't explain your problem.

... you also want a fly-back diode across your solenoid header, and across your relay coil, probably, or those NPN transistors may not be long for this world, but again not related to this question

sorry, bad schematic, pin 6 is connected to vcc

...7805 regulator probably needs bulk capacitors 10uF on its input and output too, but again probably not related...

the output has a 100nf in line with the 7805's output, maybe a little low, so I may correct that on my next revison, particularly if I have an issue with power, the input power has another pcb I created with the output being ran through a 100uf cap. clearly this board is just a small part of a much larger piece of hardware, but to keep it simple I'm just showing the schematics for this board. There's a total of 4 different circuit boards, a custom power supply, 400 pull actuator solenoid, 400 of these boards, 400 rfid antenna's and a single rfid decoder, all connected to a beaglebone via uart.

I suspect the BOOTSZ bits in the hfuse might be set to an incorrect value. Have you tried setting hfuse to 0xD9 ?

Why would you change the signature? That identifies the chip. How did you change the signature?

Almost certainly your fuses are wrong. The fuses tells it whether or not to run the bootloader. With an empty PROGMEM (ie. no sketch) the processor probably skips over all the 0xFF bytes until it hits the bootloader. Once you have a sketch there it will run the sketch.
On my Uno (which is an Atmega328P) running at 16 MHz from a crystal, my fuses are:
Low = FF High = DE Ext = FD Lock = EF

I suggest you visit http://www.engbedded.com/fusecalc to work out fuse settings.
You want the BOOTRST fuse set (that is, the high fuse should be 0xDE or something with the low-order bit clear). On the AVR chips, having a bit clear (0) means the fuse is set.
I have a bootloader programmer sketch which not only puts the bootloader there, it sets the correct fuse bit.
I also have a chip detector sketch which will tell you the current fuse settings.

I suspect you aren't writing the fuses on the AVR correctly in some way (or at all?). Try using the "Tools > Burn Bootloader" functionality of the IDE itself (which will set the fuses as well as loading the flash). You have to make sure you pick your ISP programmer under tools as well for this to work (e.g. Arduino as ISP). See if that works any better for you.
As an aside, there are a variety of AVR online fuse calculators if you're not into reading the datasheet. For example, http://www.engbedded.com/fusecalc. I seem to remember some rumblings in recent history that full swing external crystal configurations wouldn't be supported in new silicon for the ATmega328p, but that's what I always used to pick, and I think it probably still works as a setting.
Honestly, though, the easiest thing to do is to run Arduino in verbose (check the boxes in Preferences) and borrow their avrdude commands that get displayed when you run Burn Bootloader.
Continuations...
If that (Burn Bootloader) doesn't work for you, we're going to need to see some schematics, and I'd be staring pretty hard at your reset sub-circuit and FTDI sub-circuit.
Arduino Uno bootloader wants you to talk to it at 115200 baud... see the boards file.
What do you mean "My IDE doesn't hae a 328p UNO"? Download the latest Arduino from https://www.arduino.cc/en/Main/Software and choose Genuino Uno.

Thanks vicatcu, I've ran the AVRDude in cli mode with various fusebits set and lockbits. None of the settings I try seems to work. I've also ran arduino ide in verbose mode and tried to burn the bootloader from there, I get the same thing. I used Arduin as ISP and I set the board as the pro because it uses the same microprocessor. Unfortunately as I mentioned in my post the online calculators I've found don't have the 16mhz crystal option. if you look at the  http://www.engbedded.com/fusecalc website you'll find they don't have the 16mhz crystal listed as an option on the 328p.

@Cfoote7 they do have 16MHz, it's just listed as "8.0 - Mhz" meaning 8MHz and up. I would just pick the last one in the dropdown (maximum frequency, slowest startup), also you can probably safely choose the Uno as your board in the IDE, give that a try?

@Cfoote7 You are just clicking upload when you want to load over USB right? Make sure you aren't choosing Upload using Programmer. Because that will blow away the bootloader... on purpose.

I tried burning it as an Uno, it wouldn't even load a sketch once after I did that. I switched it back to the pro and I could burn a sketch again. Also I attached my schematics, I realize the ftdi is configured incorrectly but I fixed that by connecting the pins differently.

yes I'm just clicking upload and I'm using and rs-232 adapter set to 57600 baud to upload sketches. where as I'm using an arduino for loading the bootloader

@Cfoote7 see updated answer, try Arduino Uno @ 115200 baud, p.s. don't have both your 12v and the ftdi cable plugged in at the same time with your circuit

The Uno isn't working at all even at 115200 :(. My IDE doesn't have a 328p UNO as an option. I'm stuck using the 168. I don't have anything plugged into my board currently just one ftdi or one isp at a time. although the 12v is isolated so I'm not sure how that would present a problem.

my mistake I guess the latest itteration of the uno is a 328p. for some reason though, even uploading at 115200 I still can't upload sketches after burning the uno bootloader

My IDE doesn't have a 328p UNO as an option - what IDE?


text:
How much ohm resistance I should put between tp120 base and uno?
I have set up solenoid on of based on soil moisture,
The solenoid is powered by 24 volts, so I power solenoid by 24 volt and Arduino uno by stepping down to 6 volt powering through Vin and gnd.
I have used resistance of 10k ohm but I have twice burnt em.
Not sure how should calculate resistance required of signal coming out from D6 pin to TP120 base !

Is the 24 V a DC or an AC voltage?  Can you draw a circuit diagram to clarify the connections?  [Click the Circuit icon on the edit-box toolbar, if you don't have a schematics program to use] Note, edit the question in reply

24 volt dc, I have added Fritzing

Your diagram shows nothing connected to one end of the diode - is that an omission? What have you burnt twice? The resistor?

sorry fixed the fritzing, yea I am talking about resistor.

1-2.2k comes up in a web search

Are you absolutely certain the circuit is connected as shown? I can imagine it not working if you've got the wrong value resistor, but I can't see any way you'd burn the resistor up and not kill the Ardino as well. Have you perhaps got a short from one pin of the resistor to somewhere it shouldn't be?

To calculate you need to know the maximum current the solenoid uses. The TP120 has a gain of around 500-1000. So the current going into the base needs to be 1/500th of the current going through the solenoid.
So now you know the current needed. Then you can calculate the resistance value you need with R = V/I. So R = 5 / ( <solenoidcurrent> / 500 ).
So with e.g. a 2A solenoid, you get a value of 1.2kOhm.


text:
Making WiFi hotspot for 3G network sharing controlled by Arduino
I am trying to make a WiFi internet network from 3G using Arduino as access control. I need the Arduino to act as server and control users, consumption, and connection speed. (When users connect to the WiFi, they have to enter a passcode in a webpage to use internet for a limited time,  or limited data.)
So is this possible? I still did not try anything because I can not afford to buy many objects and fail to make it work.
I am thinking of using a 3G shield and a WiFi shield, or a router connected to 3G dongle connected to an Arduino via ethernet, or a 3G shield Arduino to ethernet shield to WiFi router.
I don't know if any of these can work, so I really appreciate any guidance.

Not a chance, I am afraid (you were right not to buy things yet). Things like the 3G shield and WiFi shield don't work in the way that is needed for a WiFi hotspot like that. You're better off with a Raspberry Pi and a 3G USB dongle and run hostapd along with the other software needed for your project - things like apache, etc.
You may be able to do it with the Linux portion (OpenWRT) of an Arduino Yun with a USB 3G dongle attached, but it would be sluggish. Best to stick to something with enough processing to do what you want, which means a Raspberry Pi or similar.

What you want (on at least an ARM board) is a captive portal, which catches and releases new users if and only if they pass the required challenge. There are numerous software packages for this. If you use a pi, and need to do something with the GPIO pons, have a look at the WiringPi project, which is much nicer than python's silliness. 'Inspired by Monty Python' ... indeed.


text:
Arduino Skill Stop Push button error
I made a skill stop game from Arduino Uno and a pushbutton.Here is the code:
byte led_one=2;
byte led_two=3;
byte winner_led=4;
byte led_four=5;
byte led_five=6;
byte pushbutton=12;
byte score=0;
int pushbutton_value=digitalRead(pushbutton);

void setup()
{
// put your setup code here, to run once:
   pinMode(led_one,OUTPUT);
   pinMode(led_two,OUTPUT);
   pinMode(winner_led,OUTPUT);
   pinMode(pushbutton,INPUT_PULLUP);
   pinMode(led_four,OUTPUT);
   pinMode(led_five,OUTPUT);
   Serial.begin(9600);
  }

void loop()
{
// put your main code here, to run repeatedly:

  for (int x=1;x<=6;x++)
  {
    digitalWrite(x,HIGH);
    delay(250);
    digitalWrite(x,LOW);
    delay(250);
    if(pushbutton_value==HIGH && x==winner_led)
    {
       score+=500;
    }
    else if(pushbutton_value==HIGH && x==led_one)
    {
       score+=100;
    }
  }
 Serial.println(score);
}

My Problem is that Whenever I push the button The Serial Monitor is printing out the wrong score

It'll even notice that push button is pressed? I wonder how - the only reading is in pushbutton_value initialization. Also if you have INPUT_PULLUP, you should be checking for LOW as button should be switching ground.

LOW not working too

Well, more specifically: Where do you read the current state of the push button?

To the pushbutton_value variable

And when this digitalRead happens?

What do you mean

This happens once after the reset: int pushbutton_value=digitalRead(pushbutton);. Never ever again (except if you reset the MCU).

What should the score be? How do you want the scoring work?

The initialization of int pushbutton_value should be done after the IO has been stetted (in the void setup() after pinMode(pushbutton,INPUT_PULLUP);)

I wonder why you initialized score as byte! Change it to int. As you can see when you Serial Print your score value doesn't cross 256 because the largest value a byte can have is 256 but you are summing score to 500

Hmm after I did this It still isnt working

digitalread your pushbutton_value in the loop, and whats was the output before..its still not crossing 256?

it is 0 now. What should I dp?

Could you please spoon feed me the code

How to predict the score without counting the number of pushbutton_value==HIGH recorded for the x==winner_led and x==led_one events ? Add 2 integers counters to follow those events.


text:
What would be a good way to identify items spending as little as possible?
I'm a software developer for quite some time and now I'm going to start developing for Arduino. My question is related to technology I can use. It's also my first time posting here, so if this site is not the proper place for this questions would you tell me which one I could use to get this answer?
My problem:
I need to identify items within a certain range (~3ft). So I thought about a RFID tag on each item and a reader. The problem with that approach is currently the price. The lowest price I found for RFID tags are about US$0.09 per unit. Which is way too much for this project. up to US$0.01 per unit would be acceptable.
Is there any other way I could identify these items, based on range, not being directed to the reader's laser, that would be cheaper?
I though also about something like stores do with their products to prevent theft. Adding a plastic thingy on their clothes and those totems alert if an item with that plastic thingy passed through.
I appreciate any help :)
Thanks
EDIT
Imagine a bag and products being thrown inside this bag. In my mind I'd have a mechanism in which there would be like a rim around this bag that reads the products information. That rim would be a RFID (just for illustration's sake) reader.
Items would be thrown inside this bag, sometimes plenty of items at once. And they all need to be identified.
Something like this:

I'm not actually going to implement this solution on a bag, but I think it perfecly illustrates my point.
I hope I was able to clarify the problem now :)

The "plastic thingy" uses RFID.

@IgnacioVazquez-Abrams cool :) so I think I'm on the right track here :) Would you know of any alternatives to RFID in this case or at least cheaper RFID options? As I said US$0.09 won't work. Thanks.

How about a barcode reader and print barcodes on labels to stick on your things?

Print QR codes on the objects and use a webcam to read them. PS 3ft is way to far away for rfid anyways.

@Majenko the problem with that is I'd need to directly scan it, wouldn't I (at least AFAIK)? and as I mentioned that's not something that can be requested. Once the item goes through one specific area it needs to be identified. Thanks

@Gerben the problem with that is I'd need to directly scan it, wouldn't I (at least AFAIK)? and as I mentioned that's not something that can be requested. Once the item goes through one specific area it needs to be identified. Thanks

What do you mean with "directly scan it"?

@Gerben well, using a scanner directly on the QR code, right? The only "variation" of QR codes I know work like, but if there are others please let me know... As I said I need to work on a range basis (like RFID) not on the user scanning an item. Imagine a conveyor belt with the factory's irregularly shaped products rolling over. The QR code might be facing up, sideways, down, etc... there's not way of knowing, so in that scenario I'd need something to identify the items by range, not "directly scanning" its code. Thank you.

It would be helpful if you were less vague on the application you want to use it for. You solve the upside-down problem, by having more than one QR code, or by having multiple scanners, or some way to flip the item, so you can check both sides. You don't have to put the scanner near the QR code. Just use a webcam and some computer-vision software. That way the QR code can be anywhere on the conveyor.

@Gerben I understand, I'm not looking for ways to fix the item's placement on the conveyor belt, I know that could be arranged in other ways. I need something to identify a product without being required to directly scan it. Please check my updated answer, hopefully it will make things clearer.

I'd place a few cameras around the perimeter of the bag-entrance. No need to "directly scan" it.

@Gerben Yes, but you still have the case in which two products thrown inside the bag at the same time have the QR code facing each other, something that would prevent the cameras to read it. Thanks.

How about using NFC?

@dhimaspw Thanks, I though about that, but the prices I found are even higher than those of RFIDs... I tried most Chinese sites and the prices are higher, unfortunately...

Is there a way to re-use the RFID tags? Or maybe transport the bags in a cardboard boxes (with a label), so the box itself can be scanned?

Seems like you're stuck in "requirements hell". In my theorie this means that your requirements are too strict, and you or your client won't let go of these requirements.
It can help to do a research, set up some "research questions". And if possible with some sub questions, like:
"How can we measure multiple objects at a price of only 0.01$ per object. Withouth having direct line of sight to all sides of the packaging."
With sub questions:

What techniques are available to identify objects.
In what environment will this system work?
How do other companies detect Products?
What techniques fit these requirements and environment.

And if none fit at question 4

How can we change the requirements or environment to have one technique fit.

The idea is, that after the research, you probably have a valid answer. But also that you can convince your Boss/client (or yourself), bases on your research, what solution is acceptable, even if it means altering the requirements.
You may also want to check how other companies do this, since it's a pretty common thing to identify objects etc.

For us, it is extremely difficult to say whatever will fit your needs. And you'll most likely have to adapt something.
To start off, you will either need some kind of vision or RF. But any RF tag is most likely to be too costly.
So you're either stuck with vision or increasing the price limit.
With vision, usually you either require some kind of barcode or qr code. Or you'll have to detect the object itself.
Another wat could be to differentiate on the objects' variables. Like check the weight, color, conductivity or even shape. This could be tricky, but not unlikely.
Mind that it also depends on what items you want to detect.

Well, I agree that my question was lacking information, but research was done and that's why the RFID solution was commented here. After much research RFID was found to be a suitable solution. The problem is the price. The requirements are there, I didn't specify them all when I first posted, but they are there now. So even though RFID does solve the problem, it is at a too high price per item. That's why I'm looking for solutions with the same capability that are cheaper. Thanks for your answer.

Well, if there is a price restriction, how comes that RFID is found as a suitable solution? Since, it's not a viable solution, based on price.

But, my point is, that you should check out the options you have and present this options to whoever wants you to develop this. So the conclusion of your research will be: "You either have to pay a few cents extra and get RFID working OR you can use vision (using QR or something specific), since it's cheap but will require the label to be visible.

Paul, thank you for your comments. RFID was found to be a suitable solution technically, when it came to price it was rejected. The only reason why I said that was to explain what was needed for this project (RFID suits the needs). As to "paying a few cents extra" is impossible since it would render the project inviable. Answering your other comment, that is not possible as well. I'm going to try to use photoshop to draw exactly what I mean, I think I'm not being able to explain myself properly. Do you know of any tools to prototype I could use? I'm gonna start drawing on PS for now. Thanks.

You could describe the environment a little better. But, if RFID is the only technical possible solution, but it's not economical viable solution, it means that there is no solution ;D

My point being that your requirements have to change (or find a more practical approach, but that would require an awful lot of knowledge into the environment and probably even reshaping some requirements)

Well, yes, but I never said it was the only possible solution. Just that it was one that we found... hence why I'm here looking for a cheaper technology with a functionality similar to RFID. I'm going to update my post and explain in details what I need. :) I think now the example will be clear... :)

If there was something like RFID, but 10x cheaper, it would've been more common than RFID :p (or actually, nobody would use RFID, right?) I have no other solution as altering the requirements (by proving that the current requirements are too strict). And if that's impossible, you should reconsider your project. Trying to do the impossible sound honorable, but in practice it'll get you nowhere.

And I get the idea of detecting items that are being put in a bag. But you don't tell why you want to identify these? Are you making an "automatic shopping cart" or another way to sort items? I don't see in what context it will be used.

I don't have enough reputation here to start a chat, could you? I think it will be better. Thanks anyway :)


text:
Arduino Leonardo - disabling the debugger port
My Sketch program is working perfectly as a specialized keyboard application on the Leonardo. I want to disable the development tools drivers from the USB, (COM PORT) leaving only the HID Keyboard drivers.  I understand I will need to use the Arduino ISP or other method to load my code.
Is there any way to disable the drivers for the development tools from the on board USB, leaving just the HID drivers?

Other than modifying the core? (Which, BTW, doesn't affect the bootloader)

@IgnacioVazquez-Abrams It would affect your ability to (easily) get into the bootloader since that relies on opening the (now non-existent) serial port at 1200 baud to trigger a reboot.

Never could get that to work. I just use Sparkfun's bootloader, which uses a double-press of the reset button to put it in programming mode.

There is no easy way, no. You have to reprogram the core to break the connection between the USB interface and the CDC/ACM driver. That means working out a new set of descriptors, deleting chunks of code, patching around the newly created holes, etc.

I was afraid of that...

Is this driver code publicly available somewhere?

It is on your computer.


text:
I would like to add a RGB led strip to my arduino alarm system
I am new to programming and would be grateful for any helpful answer...Thank you
I used a ping sensor, a piezo buzzer and an RGB strip. I used the Schematic from Adafruit Learning System..
Here is my code:
#define trigPin 5
#define echoPin 6
#define RED_PIN    10
#define GREEN_PIN   11
#define BLUE_PIN  9
int Buzzer = 3;

void setup() {
    //set pinModes for RGB strip
    pinMode(RED_PIN,OUTPUT);
    pinMode(BLUE_PIN,OUTPUT);
    pinMode(GREEN_PIN,OUTPUT);

    pinMode(Buzzer, OUTPUT);

    //reset lights
    analogWrite(RED_PIN,0);
    analogWrite(BLUE_PIN,0);
    analogWrite(RED_PIN,0);

    delay(5000);
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(Buzzer, OUTPUT);
}

void loop() {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance >= 80 || distance <= 0){
        Serial.println("No object detected");
        digitalWrite(Buzzer, LOW);
    } else {
        Serial.println("Object Detected");
        tone(Buzzer, 1000); // play 400 Hz tone for 500 ms
        delay(500);
        tone(Buzzer, 10000); // play 800Hz tone for 500ms
        noTone(Buzzer);
    }
    delay(300);
}

I think you need to be more clear about what you want to do with your RGB lights.

@deltaray I would like the rgb led strip to flash when the sensor is triggered, I am a novice at programming..

How do you have the LED strip connected, and what sort is it? A circuit diagram would be useful.

Would pictures work or do you want schematic

It really matters what type of RGB lights they are. Specifications like brand of lights or the chip that is used on the light strip, whether they are analogue or digitally addressable, how many lights there are on the strip and how many wires the strip has an what the wires are labeled would be a good start.  For instance, Neopixels from Adafruit are one type of digitally addressable light strip that uses its own protocol. A 5050 chip represents an analogue strip in which all colors would be the same at the same time.

The Led that I am using is 5M 5050 RGB SMD 300 LED Non-waterproof Change Color 12V Light Strip 24Key Remote

Also I am using a 12 volt source on the Vin for the RGB leds

An interesting problem with the Arduino paradigm is that not only do you need basic programming knowledge but you also need basic electronics knowledge.
On the plus side, there are plenty of good tutorials where you can over look these issues if you follow the tutorials step by step.  That is, get exactly the same parts and wire them up exactly the same way.  Later, if you like, you can go over the tutorial, ask questions here and discover how and why what you did works.
In your diagram:
You are implying you are using ordinary Red, Green & Blue LEDs and are going to vary their brightness using the Arduino's Pulse Width Modulation feature.
Possible problems:
You are powering the LEDs from the 9 volt pin of the Arduino.  And the LED strip in the diagram is clearly marked 12 volts.  This may work.  But is out of specification.
Also, this setup makes the assumption you are powering your Arduino with a 9 volt wall power supply.  Are you?  You could also power the Arduino with 5 volts using only the USB cable.  There would then be no 9 volts available at the 9 volt pin.  (I would avoid plugging in both power sources at the same time.  I think the Arduino design has changed over time.)
You are using a strip of Red, Green & Blue LEDs.  Which implies more than 1 of these Red, Green & Blue LEDs.  There is an upper current limit on the outputs of the Arduino.  More LEDs means more current.  Too many LEDs will damage the Arduino.  I would stick to 1 LED until you research the amount of current 1 LED takes verses the upper current limit of an Arduino output pin.

If you are not sure which LED lights you want to use, take a look at this tutorial  and use these LED lights
No, I have no connection to this video or its author.


text:
Using SPI Interrupt causes two servos to lose functionality
My Arduino MEGA clone (ATMEGA 2650) reads SPI data as a slave using an interrupt.
There are also two servos that make an arm (shoulder and elbow).

When I comment out the line that attaches the SPI interrupt, the servos
work properly.
When the SPI interrupt is attached, three strange things happen:
1) The PWM of the elbow remains at a fixed duty cycle. The shoulder works fine.
2) The shoulder PWM is somewhat jittery time-wise, I assume though that this is unavoidable with interrupts.
3) Writing an angle to either servo, (appears to) write to both servos! (In the software anyway.) So if I only write to the elbow, the shoulder will have the same value ( printed with shoulder.read() ). And vise-versa.

Again, none of those problems occur when I comment out the SPI interrupt attach.
It doesn't make sense to me though. Why would attaching an interrupt make two servos have the same value? And how can the values of the servos be the same, when only one PWM duty cycle actually changes!?
I wonder if this is a timer issue. Maybe the SPI interrupt interferes with the servo timers or something.
How can I receive SPI messages while also controlling two servos?
#include <Servo.h>
#include <SPI.h>

const float pi = 3.14159;
const float L1 = 27;
const float L2 = 27;
float c2;
float s2;
float psi;
float theta;

float angle_shoulder = 90;
float angle_elbow = 90;

volatile int arm_x;
volatile int arm_y;
volatile int puck_x;
volatile int puck_y;

Servo shoulder;
Servo elbow;

int sweepDir = 0;
int sweep1 = 0;

unsigned char spiBuffer[5];
volatile byte buffPos;
volatile bool process_spiBuffer;

void setup()
{
    Serial.begin(115200); //Initialize serial communication
    Serial.println("### SETUP ###");

    shoulder.attach(25); //5
    elbow.attach(43); //3

    // BEGIN SPI SETUP
    // Turn on SPI in slave mode
    SPCR |= bit(SPE);

    // Send on master in, *slave out*
    pinMode(MISO, OUTPUT);

    // Get ready for an interrupt
    buffPos = 0;   // buffer empty
    process_spiBuffer = false;

    // Turn on interrupts
    SPI.attachInterrupt();

    // END SPI SETUP
} // END SETUP()

void loop()
{
    arm_y = 30;

    if (process_spiBuffer)
    {
        spiBuffer[buffPos] = 0;
        // X is a two-byte value, SPI only sends one byte at a time, so merge the bits upon receipt
        puck_x = (spiBuffer[1] << 8) | spiBuffer[2];
        puck_y = spiBuffer[3];
        //Check if received message is acceptable, else throw warning and reject message
        if (spiBuffer[0] != '<' || spiBuffer[4] != '>' || puck_x < 0 || puck_x > 320 || puck_y < 0 || puck_y > 240)
        {   //Message received was corrupted
            Serial.print("SPI: Bad MSG Data!:\"");
            //Serial.print(spiBuffer);
        }
        else
        {   //Message received "OK"

            Serial.print("SPI MSG Received:\"");
            //Serial.print(spiBuffer);
            Serial.println("\"");

            Serial.print("SPI puck coords:(");
            Serial.print(puck_x);
            Serial.print(",");
            Serial.print(puck_y);
            Serial.println(")");

            // Decide on new paddle position. (x,y) of puck is 90degrees CW from AI (arm) POV, so x and y are swapped. Arm origin (0,0) is at bottom-right corner from the AI POV.
            arm_x = map((240 - puck_y), 1, 320, 5, 49); // map(value, fromLow, fromHigh, toLow, toHigh)

        }
        buffPos = 0;
        process_spiBuffer = false;
    }

    crunchAngles();
    moveArm();

} // END loop()

void crunchAngles()
{
    c2 = (sq(arm_x) + sq(arm_y) - sq(L1) - sq(L2)) / (2 * L1 * L2);
    s2 = sqrt(1 - sq(c2));

    angle_elbow = acos((sq(arm_x) + sq(arm_y) - sq(L1) - sq(L2)) / (2 * L1 * L2)) * (180 / pi); // theta?
    angle_shoulder = asin((arm_y * (L1 + L2 * c2) - arm_x * L2 * s2) / (sq(arm_x) + sq(arm_y))) * (180 / pi); // psi?

}

// Update the servos
void moveArm()
{
    // TODO: Clip servo output with serial warning
    if (angle_shoulder < -10) { angle_shoulder = -10; } // Actual min angle is about -18deg (Model HS-225BB)
    else if (angle_shoulder > 179) { angle_shoulder = 179; } // Actual max angle is about 181deg (Model HS-225BB)

    shoulder.write(180 - angle_shoulder + 2); // Shoulder increments clockwise, so subtract from 180

    if (angle_elbow < 0) { angle_elbow = 0; } // Actual max angle is about -5deg (Model SG90)
    else if (angle_elbow > 170) { angle_elbow = 170; } // Actual max angle is about 190deg (Model SG90)

    elbow.write(angle_elbow + 3); // Elbow increments clowise from

}

ISR(SPI_STC_vect)
{
    byte c = SPDR;

    if (buffPos < sizeof spiBuffer)
    {
        spiBuffer[buffPos++] = c;

        // End of message is ">"
        if (c == '>') // if (c == '\n')
            process_spiBuffer = true;

    }
}

My initial reaction is that it isn't the interrupt per se, but what you do when you detect that flag process_spiBuffer. As a test you could make that flag be set by closing a switch (which you test in loop) and see if the same problem arises. That would rule in or out the interrupts. Meanwhile you could also comment out your debugging displays and see what happens.

One problem is here spiBuffer[buffPos] = 0; - you are writing past the end of the buffer.

@NickGammon - The SPI code is based on your post, which has that same line in it :) http://arduino.stackexchange.com/a/16349/4455 , I do understand that the example code wasn't suited my purpose. For my sketch, it could indeed use some further optimization, however I believe the messages are all received properly (as realized by printing the results). I will test the flag as you said tomorrow. This is for my senior project where a PI sends data to the Arduino, and this communication issue is halting the entire thing, so I will be putting a lot of effort into fixing this.

Yes I see what you mean. But my buffer was 100 bytes. :) You are right though, I should check for sizeof (buf) - 1.

To be honest, I didn't understand the purpose of that line. Why would you set the last to 0? And are you saying it should be spiBuffer[sizeof(buf) - 1] = 0; ?

In the example code you copied from, I was sending an ASCII string, so that final 0x00 was the C-string terminator. That's all. In your case you don't need it.

See my amended answer. It all seems to work now.

You have multiple issues here. For a start, you have a buffer (spiBuffer) of 5 bytes, into which you place <Xxy> (that's 5 bytes) and then finish off with:
    spiBuffer[buffPos] = 0;

That has now overwritten some other memory.

Next, you don't seem to be detecting the "<" symbol and resetting to the start of the buffer, so if you ever get out of sync, you will stay out of sync. I suggest something like making buffPos equal to 0xFF initially. Then in the ISR:
ISR(SPI_STC_vect)
{
    byte c = SPDR;

    // exit if haven't processed last one
    if (process_spiBuffer)
      return;

    if (c == '<')
      buffPos = 0;
    else if (buffPos == 0xFF)
      return;  // ignore until we get a '<'

    if (buffPos < sizeof spiBuffer)
    {
        spiBuffer[buffPos++] = c;

        // End of message is ">"
        if (c == '>')
            process_spiBuffer = true;

    }
}

Now we use 0xFF as a "flag" that we haven't received a "<" yet. When we do, we reset buffPos to zero, ready to process the next 5 bytes. In the main loop, once we are done with processing the buffer we set buffPos to 0xFF again (rather than zero). Also you might have the ISR called before you have processed the previous one, so I put in a test to exit if process_spiBuffer is true when you enter the ISR.

I found your code to work out the arm positions confusing. For debugging this issue I would replace it with simply moving the servo to the position received by SPI, eg.
   // crunchAngles();
   // moveArm();

   elbow.write (puck_x);

Now just debug that rather than getting confused about the difference between interrupt issues and logic issues. I found once I had done that, that my servo responded without any major issues (there was a bit of jittering occasionally).

I found that I got a lot of data errors until I slowed down the sender (a few microseconds delay after each SPI.transfer) because sending SPI at high speed didn't give the receiving sketch time to put the data into the buffer.

The servo library is rather dependent on interrupts (it manually does the PWM duty cycles). I wrote a sketch a while back that controls one server by using the hardware timer (Timer 1) rather than interrupts:
const byte potpin = A0;  // analog pin used to connect the potentiometer

const unsigned long PRESCALER = 8;         // Timer 1 prescaler
const float PULSE_PERIOD = 0.020;          // 20 ms
const float ZERO_POSITION_WIDTH = 0.0005;  // 0.5 ms
const float FULL_POSITION_WIDTH = 0.0024;  // 2.4 ms

// how far apart the pulses are
const unsigned long PULSE_WIDTH_COUNT = F_CPU / PRESCALER * PULSE_PERIOD;
// minimum pulse width (-45 degrees)
const unsigned long ZERO_POSITION_COUNT = F_CPU / PRESCALER * ZERO_POSITION_WIDTH;
// minimum pulse width (+45 degrees)
const unsigned long FULL_POSITION_COUNT = F_CPU / PRESCALER * FULL_POSITION_WIDTH;

void setup()
  {
  TCCR1A = 0;          // disable all PWM on Timer1 whilst we set it up
  ICR1 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

  // Configure timer 1 for Fast PWM mode using ICR1, with 8x  prescaling
  TCCR1A = bit (WGM11);
  TCCR1B = bit (WGM13) | bit (WGM12) |  bit (CS11);  // fast PWM top at ICR1
  TCCR1A |= bit (COM1A1);  // Clear OC1A/OC1B on Compare Match,
  pinMode (9, OUTPUT);
  }   // end of setup

void loop()
{
  int val = analogRead(potpin);  // reads the value of the potentiometer (value between 0 and 1023)
  OCR1A = ZERO_POSITION_COUNT + (val * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;
  delay(15);                     // wait for the servo to get there
} // end of loop

That is for the Atmega328P, not the Mega, but you could adapt it easily enough. You could use Timer 2 for the other servo (I think).
Since it doesn't use interrupts, then having interrupts going off in the background won't affect the servo.

Example code
After considerable mucking around, I've got a simpler case working reliably.

Writing an angle to either servo, (appears to) write to both servos! (In the software anyway.) So if I only write to the elbow, the shoulder will have the same value ( printed with shoulder.read()

That's exactly what happened to me! Until ... I realized I should power the servos independently. As soon as I connected both servo's +5V and Gnd to an external power supply (and connected the ground of the power supply to the Mega) it all started working properly. So, lesson #1 is: power your motors properly!
I made up a test "driver" on my Uno using the code below:
#include <SPI.h>

void setup (void)
{
  digitalWrite(SS, HIGH);  // ensure SS stays high
  SPI.begin ();
  SPI.setClockDivider(SPI_CLOCK_DIV32);
}

void loop (void)
{
  int val;

  // enable Slave Select
  digitalWrite(SS, LOW);

  SPI.transfer ('<');
  val = analogRead (0);    // read A0
  SPI.transfer (highByte(val));
  SPI.transfer (lowByte (val));
  val = analogRead (1);    // read A1
  SPI.transfer (highByte(val));
  SPI.transfer (lowByte (val));
  SPI.transfer ('>');

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (100);
}

That reads a pot on A0 and A1 and sends the full value (2 bytes) over SPI (which is slightly different to what you are doing).
Then the receiving end (on a Mega2560) has this code:
#include <SPI.h>

const unsigned long PRESCALER = 8;         // Timer prescaler
const float PULSE_PERIOD = 0.020;          // 20 ms
const float ZERO_POSITION_WIDTH = 0.0005;  // 0.5 ms
const float FULL_POSITION_WIDTH = 0.0024;  // 2.4 ms

// how far apart the pulses are
const unsigned long PULSE_WIDTH_COUNT = F_CPU / PRESCALER * PULSE_PERIOD;
// minimum pulse width (-45 degrees)
const unsigned long ZERO_POSITION_COUNT = F_CPU / PRESCALER * ZERO_POSITION_WIDTH;
// minimum pulse width (+45 degrees)
const unsigned long FULL_POSITION_COUNT = F_CPU / PRESCALER * FULL_POSITION_WIDTH;

const byte NO_DATA_YET = 0xFF;

volatile unsigned char spiBuffer[6];  // '<' xH xL yH yL '>'
volatile byte buffPos = NO_DATA_YET;
volatile bool process_spiBuffer = false;

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

  // Turn on SPI in slave mode
  SPCR |= bit(SPE);

  // Send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // Turn on interrupts
  SPI.attachInterrupt();

  TCCR1A = 0;          // disable all PWM on Timer1 whilst we set it up
  ICR1 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

  // Configure timer 1 for Fast PWM mode using ICR1, with 8x prescaling
  TCCR1A = bit (WGM11);
  TCCR1B = bit (WGM13) | bit (WGM12) |  bit (CS11);  // fast PWM top at ICR1
  TCCR1A |= bit (COM1A1);  // Clear OC1A/OC1B on Compare Match,

  #ifdef __AVR_ATmega2560__

    TCCR3A = 0;          // disable all PWM on Timer3 whilst we set it up
    ICR3 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

    // Configure timer 3 for Fast PWM mode using ICR3, with 8x prescaling
    TCCR3A = bit (WGM31);
    TCCR3B = bit (WGM33) | bit (WGM32) |  bit (CS31);  // fast PWM top at ICR3
    TCCR3A |= bit (COM3A1);  // Clear OC1A/OC1B on Compare Match,

    pinMode (11, OUTPUT);   // OC1A is D11 on Mega2560
    pinMode (5, OUTPUT);    // OC3A is D5  on Mega2560
  #else
    pinMode (9, OUTPUT);    // OC1A is D9  on Uno
  #endif
  }   // end of setup

int xValue,
    yValue;

void loop()
{

  if (process_spiBuffer)
    {
    if (spiBuffer [0] == '<' && spiBuffer [5] == '>')
      {
      xValue = makeWord (spiBuffer[1], spiBuffer[2]);
      yValue = makeWord (spiBuffer[3], spiBuffer[4]);
      }

    // ready for another interrupt
    buffPos = NO_DATA_YET;
    process_spiBuffer = false;

    }

  // adjust PWM amount
  OCR1A = ZERO_POSITION_COUNT + (xValue * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;

  #ifdef __AVR_ATmega2560__
    OCR3A = ZERO_POSITION_COUNT + (yValue * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;
  #endif

} // end of loop

ISR(SPI_STC_vect)
{
  byte c = SPDR;   // get byte from SPI hardware

  // exit if haven't processed last one
  if (process_spiBuffer)
    return;

  if (c == '<')
    buffPos = 0;
  else if (buffPos == NO_DATA_YET)
    return;  // ignore until we get a '<'

  if (buffPos < sizeof spiBuffer)
    {
    spiBuffer[buffPos++] = c;

    // End of message is ">"
    if (c == '>')
      process_spiBuffer = true;

   }  // end of room in buffer
} // end of ISR(SPI_STC_vect)

This incorporates my suggested use of the timer hardware to do the servo positioning, rather than the servo library. There are a couple of #ifdefs in there, so you can run it on a Uno as well (it just won't do the second servo).

The servos are already powered independently and sharing a common ground with the whole project. Since the servos have the same values with servo.read(), wouldn't that make it a software issue? A software issue that only occurs when the SPI interrupt is attached.

Like I said under the question, try triggering the "interrupt part" with a switch, and feed in dummy values (which are different). I doubt the interrupt as such is causing the issue, it will be the code that runs afterwards.

Plus, I stick to what I said about the servo library using interrupts itself. If you switch to hardware PWM then it can't be the interrupts. But some debugging displays should sort all that out.

Since the servos have the same values with servo.read(), wouldn't that make it a software issue? - I don't see servo.read() in your code. I still think you are confusing the interrupt itself to the code that is executed after the interrupt is detected. That is where I would be looking.


text:
How convert eight hex characters to uint32_t using strtol() function?
I want to control 4 pins using hexa code like this ff00ff00 (255, 0, 255, 0).
strtol() function works fine with three pins like 00ff00, but when i add two extra caracters to &payload[1] variable like this ff00ff00.
((rgba >> 24) & 0xFF) is equal to 127 when it should be 255.
How to make this work?
each analog pin should be set from 0 to 255
    analogWrite(LED_WHITE,  ((rgba >> 24) & 0xFF));
    analogWrite(LED_RED,    ((rgba >> 16) & 0xFF));
    analogWrite(LED_GREEN,  ((rgba >> 8) & 0xFF));
    analogWrite(LED_BLUE,   ((rgba >> 0) & 0xFF));

    uint32_t rgba = (uint32_t) strtol((const char *) &payload[1], NULL, 16);

The function strtol() is not able to convert numbers that are larger than LONG_MAX and smaller than LONG_MIN as it uses signed numbers.
You should use the function strtoul() instead (for unsigned long integers).
Cheers!


text:
Arduino RGB component identification

Can someone help me identify this component?
Thanks in advance.

What is the purpose of identifying this product? Do you want to purchase one? Are you after the identification of the individual components or are you wanting the identity of the board?

It's an RGB led... connect GND to ground/0V and R, G or B to 5V to make the LED light up in that color?

It's a common-cathode RGB LED module. The LED package itself has 3 independent LEDs, but the board ties the cathodes together.

authors: Николай Сулима


text:
Most efficient method to turn a gear extremely slowly?
I have a gear that needs to have roughly one rotation per day.  It does not have to be smooth or consistent.  So far, the best I have come up with is to have a stepper motor with an arduino that sleeps, wakes up once an hour maybe and turns the stepper a little bit.
Which arduino should I use for this and is there perhaps a simpler method?  Is there any way to fully cut power then when powered on the arduino advances the motor and then shuts off?
Any ideas?
I want to run off of a 9v battery and get as much time as possible.
edit: adding details as requested
the rotation needs to happen slowly over the 24 hour period.  The tube being turned is a light plastic 1" diameter tube that weighs about 2 lbs.

How big is the gear and how much torque does it need to deliver? Is the load active or static? Is it ok to sleep 24 hours or whatever and then do a whole rotation?  Perhaps you should edit the question to answer the above questions, and also say something about the overall purpose and context.

ok, edited to add details.

Using a 9V battery to power a motor that will rotate 2 lbs will probably not work as those batteries have too little energy. Also, sleeping an Arduino does not reduce its current consumption much (see my answer to a recent question: http://arduino.stackexchange.com/questions/31813/how-to-make-battery-last-for-months/31815#31815).

Steppers require current - and power, due to I^2*R losses) to hold a position. Power off, they free-wheel. What kind of efficiency do you need? A stepper might not be the most power efficient.
An escapement permits or causes a gear to index one position and prevents it turning any farther. In a clock, it permits a weight-driven or spring-driven shaft to index. You'll probably want one that drives the shaft as well, probably with a solenoid.
Another option that comes to mind and doesn't need an Arduino, is a clock motor. Gear down the hour hand 2:1 and you're done. Find a 24-hour clock motor and even that gearing will have been done for you.

A worm gear might be a good option if some holding force is required

Turning of the stepper in between, will result in reduced holding torque. This might be a problem.
I'd suggest using a AA battery pack. 4 AA batteries will give you around 5V. The Arduino doesn't require a precise 5V, so you don't need a voltage regulator.
I'd suggest using something like a Arduino Pro Mini, or Arduino Micro, as those don't have USB-to-Serial chips on the board, using up power all the time. Remove the power led, and put the uC to sleep as much as possible.
If you want accurate timing, you'd want to add and RTC module.


text:
Need Help in circuit diagram of 8*8 reed switch matrix
I am designing 8*8 reed switch matrix which will be connected to Arduino. I am using Arduino Duemilanove. I have completed the matrix portion but don't know how to connect and where to connect the other elements.

I decided to use the following items:

Arduino (Duemilanove)
64x Reed Switch
64x Diode (1N4148)
20x Resistors (10K)
1x 74HC595
1x 74HC165

I don't know where to place the Resistors and shift Registers and connection from shift registers to arduino. I need help in the circuit diagram. Please help me out with the circuit diagram.
Reference: https://mtifall10.wordpress.com/2010/12/10/magnetic-sensing-chessboard/

The linked "full photo set" from your article appears to show exactly how the switches and diodes are arranged. Did you not look at the photos? Is there something about them that you don't understand? Otherwise, your question seems very strange since you have cited a reference that appears to provide a complete answer.

I have completed the circuit of switches and diodes connection. I have mentioned in the last paragraph that I need help in the connection of shift registers and resistors whose circuit diagram is not given in the reference and that is where I am stuck.

How will the various pieces be recognised by Arduino? Top-down may be a better design approach in this case. In choosing reed switches you are constrained from the outset.

You know which pieces are where when the game starts.  You track which one is removed from the board and where it is replaced.  This way, you know where the pieces are without having to identify them.  You must also have the Arduino sound a warning and refuse to play any more if more than one piece is ever off the board at one time during a move.  It also has to recognize when a piece must be removed from the board (captured) and not throw a fit then.

This answer is based on a previous version of the question

Not necessarily. You can use the internal pullups of the arduino if you're willing to accept that reading a "1" means that no piece is there and reading a "0" means a piece is there.
Connect each wire up to a pin on the arduino. If you do it wisely, step 3 becomes fairly easy.
You need to configure the pins connected to the letter wires as inputs with their pullups enabled. Set the number pins to inputs as well, but without the pullup enabled so that they are floating. The number pins will be each set as an output in sequence with the value being low (non-active number pins are set back to inputs). As you do so, you can read the pins on the letter wires and build a picture of the board.

Example
This is how I would do it just taking a naive stab at it. I'm sure there are more effective ways to do this.
Wiring:

Configure the outputs and inputs in setup:
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(4, INPUT_PULLUP);
pinMode(5, INPUT_PULLUP);
pinMode(6, INPUT_PULLUP);
pinMode(7, INPUT_PULLUP);
pinMode(8, INPUT_PULLUP);
pinMode(9, INPUT_PULLUP);
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(12, INPUT);
pinMode(13, INPUT);
pinMode(14, INPUT); //A0
pinMode(15, INPUT); //A1
pinMode(16, INPUT); //A2
pinMode(17, INPUT); //A3
pinMode(18, INPUT); //A4

Make a function to scan the rows into an array of bytes:
void scan_rows(uint8_t *rows)
{
    uint8_t i, j;

    for (i = 0; i < 8; i++)
    {
        if (i)
        {
            pinMode(i+9, INPUT);
        }
        pinMode(i+10, OUTPUT);
        digitalWrite(i+10, LOW);
        for (j = 2; j <= 9; j++)
        {
            rows[i] <<= 1;
            if (digitalRead(j))
                rows[i] |= 1;
        }
    }
    pinMode(18, INPUT);
}

Now, just call that function with a pointer to an array with 8 bytes in it whenever you need to scan the board. Each byte in the array represents one of the rows and each bit represents a column.
[moderator note: This answer appears in this thread as a result of a merge]

Use 16 digital i/o pins on the Arduino. The ones connected to a-h should be configured as OUTPUT pins. The ones connected to 1-8 should be configured as INPUT pins. Start with all of the outputs (a-h) low.
You check for a closed switch at the lower left corner by making the output pin connected to 'a' HIGH then look at the value of the input pin connected to '1'. If it's high then that switch is closed. If it's low then that switch is open.
While the 'a' output is HIGH you can check the rest of the left column by looking at inputs '2' through '8'.
I don't see any need for the resistors or shift registers, but maybe your teacher had something in mind.
EDIT: I see that by using the shift registers you need only one INPUT pin and one OUTPUT pin on the Arduino. I'll leave that for you to figure out as I think I've given enough to get you started.


text:
How to make 12V flashing LEDs using an Arduino Uno?
I have 3 LEDs powered by an Arduino; each LED has its own flash rate.
Now I want it to be powered by an external 12V power source and still have the flashing function of the Arduino?

You will need a transistor or a MOSFET to do that (one per LED). Just google that and you'll find many examples how to do it. On Arduino.SE, there have also been many questions about this topic.

Thank you very much! I tested it and it works perfectly! :D

Use a N-channel MOSFET, wire load to drain pin, source to (common) ground, and place a 1 kilo-ohm resistor in series with your arduino pins. Bear in mind that MOSFETs respond to voltage, not milliamps, on the gate - get one that responds well to 5V logic.

You do not need a series resistor with a MOSFET (although it does no harm). If using a bipolar transistor it is essential.

@Milliways We discussed that before. Different strokes I suppose.

Or you could use a relay. Many small ones available for a couple of dollars.

Using a relay for such circuit would be just annoying because of "clicking" on relay.

Hmmm, I didn't read that that was a criteria, not to mention that there are small, quit, solid state relays.

As has been mentioned, you could use an N Channel MOSFET, but preferably look for a Logic Level MOSFET.  These are capable of being turned on by lower voltage levels such as on the pins of an Arduino.
Having said that, i have used two non logic level MOSFEt's in Arduino projects successfully.  They are the IRF3205 and IRF 520 - both are readily availalable and will work OK with the Arduino output pins for your low-current-driving-an-LED requirement.


text:
Questions on how to connect Arduino to Matlab through the serial port
I have an Arduino board with Intel Edison on it. I have tried to read data in Arduino from MatLab through the serial port. I'm sure the Arduino board is working because when I use the serial monitor from Arduino, it shows the data read from the Arduino board. My command is like this in Arduino:
   reading = Wire.read();
   Serial.println(reading)

I got errors in Matlab when I tried to work with these piece of code:
   s=serial('COM4');
   set(s,'BaudRate',9600);
   fopen(s);

MatLab complains that "Port: COM4 is not available. No ports are available.
Use INSTRFIND to determine if other instrument objects are connected to the requested device." I have tried with "instrfind()" in matlab and got this:
   Instrument Object Array

   Index:    Type:     Status:   Name:
   1         serial    closed    Serial-COM4
   2         serial    closed    Serial-COM4
   3         serial    open      Serial-COM4
   4         serial    closed    Serial-COM4
   5         serial    closed    Serial-COM4

I still can't get any clue on this. Can anybody help me?

I'm not a fan of how Windows handles COM ports.  I think the most successful applications scans all the COM ports and identifies with a connected device through proprietary means (for example, maybe the application is looking for the company's name as a response).  I might try to reboot (its Windows after all) with out the Arduino plugged into the USB port, bring up the device manager and open the COM section and watch which COM becomes available when you do plug in the Arduino's USB cable.  Then try connecting to that COM with matlab. Don't use anything else that may connect to that COM port.

Hi, I can't believe I forget "reboot the system" for this. Your idea works. Thanks very much.

Great news.  In order to count this question as solved: I can copy the comment to the Answer box where, if you would be so kind, accept it.

I might try to reboot with out the Arduino plugged into the USB port, bring up the device manager and open the COM section and watch which COM becomes available when you do plug in the Arduino's USB cable. Then try connecting to that COM with matlab. Don't use anything else that may connect to that COM port.


text:
Getting a reset error on a WEMOS D1
As a learning effort, I am trying some sample code on my WEMOS D1, which is basically an Arduino compatible board with a built-in ESP8266 (Wi-Fi module).
This is the output of my Serial Monitor:
1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld
Initializing Wifi...
Start printMacAddress
 ets Jan  8 2013,rst cause:4, boot mode:(1,4)

wdt reset

It stops there and I see no more messages. Below is the code I am trying (from https://www.arduino.cc/en/Guide/ArduinoWiFiShield):
#include <SPI.h>
#include <WiFi.h>

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(115200);
  // attempt to connect using WEP encryption:
  while(!Serial) ;
    Serial.println("Initializing Wifi...");
    printMacAddress();
    // scan for existing networks:
    Serial.println("Scanning available networks...");
    listNetworks();
}

void loop() {
  delay(10000);
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void printMacAddress() {
  Serial.print("Start printMacAddress");
  // the MAC address of your Wifi shield
  byte mac[6];
  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("MAC: ");
  Serial.print(mac[5],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.println(mac[0],HEX);
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();
  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);
  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

I am not a hundred percent sure, but I think this started happening when I connected D8 (Digital Pin 8) to a relay.  I later read that it has a specific use (to flash firmware I think). The error message appears to point to something called a "WatchDog Timer", but I am not even sure what to eat that with. :-)
There are no error messages in the IDE and it even uploads fine. So why is this happening and how do I fix it?
TIA!

Can you disable the code for setting the relay pin as an output? I once got watchdog reset for setting reserved pins as an output. Which prins are reserved, can differ per board.

There is no such code in the above.  This happened in another program and I thought I may have munged the board.

Ah okay, I was unsure if you left out that piece of code, since it was described in the text, but not in the code. Given that it still uploads, I think it's unlikely you broke something, since, I assume, the uploading should break if you break the bootloader pins.

WEMOS D1 is not an Arduino board. It's a NodeMCU clone.

@dda You're right, I meant an Arduino "compatible" WEMOS D1.  Turns out it is not even a WEMOS but a clone made by Qunqi. :-)

If Watchdog timer is the cause of reset that means there is at least one place in your code that runs too long without allowing subsystems to do the background tasks. It might be possible the part of your code causing the problem is:
while(!Serial) ;

Instead that loop use:
while(!Serial)
  delay(100);

so the background tasks will get the chance to be exectuted during the while loop.
EDIT:
In fact you can completely remove that while loop as it is not necessary. There is a possibility !Serial is always true so the loop never ends. And I suggest you using 74880 instead of 115200 so you can see the debug messages sent automatically by ESP8266.
END OF EDIT
However, if that is not the part of the code that causes the problem (and I think it is not) then the problem might be for loop where you list networks. You can check if that is the problem by adding a small delay inside the loop as follows:
for (int thisNet = 0; thisNet<numSsid; thisNet++) {
  delay(1);
  Serial.print(thisNet);
  Serial.print(") ");
  Serial.print(WiFi.SSID(thisNet));
  Serial.print("\tSignal: ");
  Serial.print(WiFi.RSSI(thisNet));
  Serial.print(" dBm");
  Serial.print("\tEncryption: ");
  Serial.println(WiFi.encryptionType(thisNet));
}

If the problem will still exist then you can add a few more delay(1); statements through the code.
Instead of delay you may use yield(); which is the same as delay(0);.

Thanx @Chupo_cro but none of those worked.  So, I started commenting out stuff and apparently the problem is at two places (the program works without these two).  The first is the line: WiFi.macAddress(mac); and after that this line: byte numSsid = WiFi.scanNetworks();  Which pretty much makes this program a zero....


text:
How to add Attiny13 to Attiny board profile in Arduino IDE 1.6?
Several months ago, I asked how to add (or where to get) Attiny13 to the list of boards in the Attiny package available in github: https://github.com/damellis/attiny In post 1.5 IDE, the package is installed by adding repo's JSON file to boards manager, as described in this post: https://arduino.stackexchange.com/a/23056/2955
Nowhere it says how to modify the files, not at all. And the package doesnot contain Attiny13 info.
The answer to my question was to do it myself and make a pull request. So ok, but how do I do it? I don't understand those files. The JSON file refferences some SHA-256 named zip files. That's hardly something that can be clearly and simply edited.
Can anyone tell me clearly what do I have to do to get Attiny13 working within that profile?

Did you manage to fit an Arduino core inside the smallish ATtiny13 ? :-O

this is the official Arduino IDE 1.5 3rd party Hardware specification. It is still valid for 1.6.
It is probably lots easier to just copy past a similar board; rename the board ID and try.
Note that for a change in the boards.txt to be seen in the Arduino IDE you need to stop and start the Arduino IDE.

But where can I find the boards.txt file? Won't it get overwritten upon next update?

The first part of the document is about the folder structure so that tells you where you can find the boards.txt. Unless you upgrade or deinstall and reinstall the boards.txt will not be overwritten. But it is always safe to have your own copy (for instance on github)

You can easily add entries for the ATTiny13 to the IDE, but won't show in the same listing as damelis's ATTiny cores, as he hasn't added the ATTiny13 yet.
Here is what I have found for ATTiny13 Arduino core files, working with  boards.txt, loading them into the IDE, etc.  The boards.txt is all laid out, just drop it into your personal workspace per the directions provided.
https://github.com/MCUdude/MicroCore
How to install
Boards Manager Installation
This installation method requires Arduino IDE version 1.6.4 or greater.
Open the Arduino IDE.
Open the File > Preferences menu item.
Enter the following URL in Additional Boards Manager URLs: https://mcudude.github.io/MicroCore/package_MCUdude_MicroCore_index.json
Open the Tools > Board > Boards Manager... menu item.
Wait for the platform indexes to finish downloading.
Scroll down until you see the MicroCore entry and click on it.
Note: If you are using Arduino IDE 1.6.6 then you may need to close Boards Manager and then reopen it before the MicroCore entry will appear.
Click Install.
After installation is complete close the Boards Manager window.

This will get you quite a lot of functions, configurable clock speeds, etc. The readme for this project helped me quite a lot  in understanding what is going on inside the box and how I can enable only the Arduino core functions that I want, to save space.
Microcore is based upon :
sourceforge.net/projects/ard-core13/files/latest/
And both projects have code updates as of this summer.
For other ATTiny (I'm using an ATTiny85 sometimes since for some things I ran out of space on the ATTiny13)
github.com/damellis/attiny
This will get you:
ATtiny 25 (8 pin)
ATtiny 45 (8 pin)
ATtiny 85 (8 pin)
ATtiny 24 (14 pin)
ATtiny 44 (14 pin)
ATtiny 84 (14 pin)


text:
wire.h onReceive only triggering once
I am writing a program to emulate a LCD driver chip (PCF8576) in a piece of equipment where I need to replace an unobtainable LCD display.
I have wire.h set up and the code in place to decode chip commands and load the segment data to an array.  That all works, and I can take that data and drive a new LCD just fine.
My problem is that the onReceive handler only triggers once.  To get it to be armed and trigger again I need to press the reset button on the Uno board.  I put code in to pulse an output pin and can verify with a scope that the onReceive only runs once.
When I just began the coding last week the handler would trigger each time the equipment would write to this particular I2C address, and I can tell the equipment is operating correctly since an Arduino reset will then result in the onReceive event triggering again.
Does anyone have any clue what's happening here?  I tried commenting out most of my code but it still won't trigger on each receive.  Obviously there's something subtle I changed that I'm missing, but what?

Please edit question and put the reduced code into the question.  Accompany the code with a diagram or brief outline of circuit.

Try this; https://www.arduino.cc/en/Tutorial/MasterWriter

You are correct and that was the second part of the problem. The first part was that my code wasn't always retrieving every byte and this was hanging up the OnReceive function. Once I fixed that bug I found something very close to what you mentioned. On rapid device writes my handler routine didn't finish fast enough and thus could miss updates. What I did was to streamline the routine to take minimum time and that worked as the sending processor needed time between updates itself. In testing this works fine, what I did was to toggle a port pin and look at the I2C bus and that pin and could verify I was cleared out of the routine before the next update could come in. If it was close I would have gone to assembly for that routine but it turned out ok in this case. Thank you for your analysis!

If you have solved your own problem, please accept your own answer.

I looked at what docs I can find (not much) for 'onReceive' handler, but have not looked at the code itself.  I would ask, does the system keep running in spite of the fact that your handler isn't being invoked?  I'm asking if the bus is actually working after the first invocation of the handler? My guess is no. I also guess this ("onReceive" handler) has never worked as designed (hoped for?)
Also it sounds like you have a DSO scope, neat. Decades in electronics and I still get fooled by them (or the software:) now and then.  So make sure it's setup properly. Sounds like you do... but...
Does the i2c bus have only this one device?
I've found that 99.99% of my problems turn out to be chip configuration.  Improper interrupt or mask bits, etc. If it's driven by an interrupt, then it almost has to be the chip's interrupt configuration.  Of course if your code goes awry then it could change some of these bits that control the micro's operation and most can also write over the interrupt vector table.
Since it works after a reset, once, it may be wise to track down what happens in your particular micro's configuration after the reset, compared to what you change to get it to work.  Some of the parts of the micro I use (328p, maybe you also) have to be reset after an interrupt.
A last but not least option, since I'm not familiar with the function is to look at the assembler and see if it's resetting the required interrupt enable flags or masks. Most of these handlers end with some type of return from interrupt instruction that enables the interrupts and returns.  Generally alleviating the programmer of that task.
Best of luck :)

An Arduino as a I2C Slave to replace something in a device often fails. The Arduino uses hardware and software, while I2C chips use only hardware. The Arduino as Slave is often recognized on the I2C bus because it acknowledges to its I2C address. However, as soon as data needs to be transferred, the Arduino stretches the clock signal to create some time to call the onReceive function. Do you know if the I2C Master controller is able to handle the clock pulse stretching ? Sometimes it is a software I2C, and almost no software implementation takes care of clock stretching.