How to choose a transmit pin in the IRremote library for an Arduino Uno?

As the pin does not appear to be able to be defined when creating an object from the IRsend class, it seems as if you will have to modify the IRremote library itself.

I recently had the same problem with the USB Host library, see Change select pin of USB Host library. It is annoying when you can't define the pin(s), that a particular library uses, yourself... However, the authors of the library probably have their reasons for doing so.

Looking through the various headers of the library, I found in boarddefs.h on lines 134-138:

// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc
// ATmega48, ATmega88, ATmega168, ATmega328
#else
    //#define IR_USE_TIMER1   // tx = pin 9
    #define IR_USE_TIMER2     // tx = pin 3

So, the line to change, for the Uno, would seem to be line 138 in boarddefs.h

    #define IR_USE_TIMER2     // tx = pin 3

However, it is not, as that merely states that for the Arduino Uno IR_USE_TIMER2 is used...

Looking further down to where the Timers are defined, you will see the section for Timer 2, on line 146. In that section the transmit pin, for a number of versions of the Arduino, is defined as TIMER_PWM_PIN on lines 189-197:

#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \
|| defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \
|| defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \
|| defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \
|| defined(__AVR_ATmega164P__)
#   define TIMER_PWM_PIN  14             // MightyCore
#else
#   define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc
#endif                                   // ATmega48, ATmega88, ATmega168, ATmega328

You will have to change this line in the library, Line 196 in boarddefs.h:

#   define TIMER_PWM_PIN  3              // Arduino Duemilanove, Diecimila, LilyPad, etc

You could try changing the 3 so that you can use another pin. It might work. For example to use pin 5, en lieu of pin 3, change the 3 to a 5, like so:

#   define TIMER_PWM_PIN  5              // Arduino Duemilanove, Diecimila, LilyPad, etc

Be careful not to choose a pin that is used by something else, AND I think that the pin will need to be PWM capable.

Note that the definitions that are in boarddefs.h used to be in RemoteInt.h, in earlier versions of the library. See this comment at the very top:

// This file contains all board specific information. It was previously contained within
// IRremoteInt.h

So, make sure that you have the latest version of the IRremote library.

The above hack should also work for the Mega2560 as is uses the same timer, Timer 2, see lines 68-71:

// Arduino Mega
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
    //#define IR_USE_TIMER1   // tx = pin 11
    #define IR_USE_TIMER2     // tx = pin 9

Other boards are also defined in this file. If you have another type of board, the timer may be different, but the process to find which line to change would be very similar...


What are the advantages of "Arduino compatible" boards

While Arduino is an open source system, "Arduino" is a trademarked name and may only legally be used for products from the Arduino's originators or licensed suppliers. Arduino are quite clear about this requirement - see here - Logo and here Trademark
and here What makes an Arduino board an Arduino? and FAQ

As a result, compatible microcontroller boards are legally required to NOT identify themselves as being "Arduinos", so the term "Arduino compatible" is about the most that even an Arduino-identical clone can claim.

As karan notes, some Chinese sourced Arduino compatibles "have issues".
however, I have had no problems at all with Arduino compatibles manufactured and supplied by this Chinese supplier. As well as the basic devices they sell various interface boards (shields) and related equipment. Prices are astoundingly low, free postage is included in many cases (about 2 to 3 weeks delivery time to New Zealand) or you can pay for courier delivery. I buy Nano or Pro-Mini compatibles devices  - usually in batches of 10. As you will see -  Nano compatible costs $US3 each in 10's. Pro Mini compatible is currently $US1.68 each in 10's. !!!
Uno compatible here is $3.80 in 10s.  The voltage requlator may be a different type than than on 'real' Arduinos (but work OK) and versions with a USB-serial bridge IC use a non FTDI IC and you need to source and load the correct (freely available) drivers.

NB: (1) I have NO commercial connection with this company except as a very happy customer.
(2) I'd expect you to have no problems with these or other products from them but I of course have  no responsibility for what they sell.


How do I communicate with the Uno using R through RStudio?

If RStudio has serial support. Yes, it can talk to a Uno. If it does not. No.

This is really a question about RStudio (and actually just pure R), not arduinos.

Furthermore, RStudio is just an IDE. Therefore, no, RStudio can not communicate with an arduino, compile a program, or do much of all aside from edit source-code files. RStudio does not run your code at all. It uses an external interpreter to run your source files.

R, on the other hand probably can talk to serial interfaces. The fact that you're using RStudio is entirely irrelevant.

I'm not familliar with R, but a little googling leads me to think that R can talk to serial interfaces without too much trouble, though I have not been able to find any information about doing so on windows. What platform are you using?


Need a component to connect a 9v water pump

Yes, a MOSFET should work just fine. As others have said in the comments, you just need to make sure that it's rated for your desired voltage and current, and that it's threshold voltage is low enough (around 2.5V) that the Arduino is able to drive it to saturation with a logic level 1 (5V).

I've used this one (rated at 60V and 30A) in various projects:

https://www.sparkfun.com/products/10213


Interfacing 9-Axes Motion Shield with RPi and WiFi Shield

Q1. The official Arduino page says that the shield doesn't have any external power source and can only be powered up by stacking on top of an Arduino board. How can I use this shield with a Raspberry Pi?

By providing the right power to the right pins.

  Q2. A page here shows that it has support for the Ethernet Shield but doesn't mention WiFi shield anywhere. Does this mean that I cannot use my WiFi shield with it? I plan to stack the 9-axes shield on top of the WiFi shield which in turn is stacked over Arduino Uno.

No, it says it is compatible with the Arduino Ethernet which is not a shield, it is an Arduino.

What other shields you can use it with depends on what pins those other shields use.  Look at the schematics. Read the manuals. Do some leg-work.


if two arduinos are connected by I2C and one of them is using an ethernet shield, does that grant both of them access to the internet?

I2C does not automatically share resources between two connected devices. You would not be able to share an Internet connection from a Mega connected via I2C to another Mega which has an Ethernet shield.

However, you could write code for both Megas that implements a two-way communication in which the non-shield Mega sends requests or commands to the one with the Shield, and then passes that data back to the non-shield Mega.

However, you, as the coder, would be responsible for designing such a protocol and implementing it. It would be quite a task probably.


Deriving the exact relationship between PWM and steering

Where do I learn more about this feedback mechanism?

It depends on the kind of feedback. You can have absolute or relative feedback. Relative would be, for example, to use an encoder on each wheel to find out how much it has turned. Absolute would be using a compass to know exactly what direction the vehicle is facing at any time.

Purely from a physics perspective, considering an ideal environment, how do I derive a relation between rpm and the steering angle?

If you know how much each wheel has turned then it is really just simple trigonometry. You have two arcs that are the same proportion around the circumference of two circles. The circles must have the same centre point. Well, I say "simple" - that's a relative term. And of course it depends if you are moving like a car (i.e., turning while moving forwards) or like a tank (turning on the spot) as to whether such calculations are particularly meaningful.
But then of course that's only if you actually know the RPM. Which requires feedback.
There is no easy relationship between PWM and the angle turned. This is because PWM does not define the RPM:

PWM defines the current
The current defines the torque
The torque defines the acceleration (and ultimately maximum speed) under different loads and conditions.

Those loads and conditions change depending on lots of factors. With no way to change the angles of the wheels they will need to slip on the surface as you turn. That adds friction and varies depending on both the speed at which you turn, the angle you turn through, and the surface you are driving on at the time. A high friction surface will both increase the power transfer and at the same time require more power to turn. A sharper turn angle will slip more and require more power to overcome the friction.
It's a very complex relationship with far too many variables. Which is why cars have steering mechanism to change the angle of the wheels, and some vehicles have rear-wheel steering as well to change the angle of the rear wheels to reduce slip and friction (such as the Porsche 911 and many large heavy vehicles), and why London cabs use "Ackermann" steering which gives each wheel a different angle while turning to increase the angle the vehicle can turn through so it can turn in the road easier.
So all in all if you want to know what direction you are pointing at any time, although it's harder to interface with and use, and may be a little more expensive, a compass or other absolute rotation sensor is the way to go.
If you want to turn to a specific angle, (or turn through a specific angle, which is just a relative change between two specific angles) then it's a case of "move a bit" then "see what angle I'm at" then "move a bit more" and "see what angle I'm at".
You could either use a simplistic approach where you always move in discrete steps, or use a PID to calculate what would be a good amount to turn to get you closer and closer to the desired angle depending on how far you turned last time.


Reading and processing a PWM on AtTiny45

You don't need to read the duty cycle, just the time that the PWM signal is high. First wait for the input pin to go high, then start a timer, wait for the signal to go low again, and finally read the timer value. If other tasks need to be performed concurrently then use pin change interrupt to detect the high and low transitions.

If the ATtiny is running Arduino software then the solution is even easier - just use the pulseIn() function.

This technique works for all PWM values except 0 and 255. With these values the pin stays low or high permanently, so there are no transitions to time. The easiest way around this is to simply avoid transmitting 0 or 255.

Alternatively you could pass the PWM signal through an RC filter to produce a 'DC' voltage, then read it with the ADC. However this will slow the response time down, and the signal will produce intermediate values as it goes from one voltage to another. To get good resolution the RC filter would need to have a long time constant, and you might have to average several readings to get a stable value.


Unreliable communication with low baudrate on Leonardo

I suspect that the RS-485 interface in your servo is what is at fault.  Nothing to do with the Arduino or your communication, or software.

Without knowing more about the servos and how they are wired internally it's hard to be certain, but I can assume:

The servo has some kind of controller in it which communicates over the bus
That controller may or may not directly control the direction pin on its interface

It's the latter that is critical. There is a way of wiring up a MAX485 that automatically controls the direction pin - immediately you start sending data it asserts it into TX mode. The trouble comes when switching back to RX mode - there's a few ways of doing that:

Shortly after the last bit of a certain value (0 or 1) has been sent (the bit stream keeps a capacitor charged)
A certain time after the start of communication.

The first method is usually more reliable across multiple baud rates, but can be sensitive to the values of the bytes sent - if it relies on a 1 being sent to keep the capacitor charged and a number of 0 bytes are being sent it won't see the 1 that keeps the transmit mode open, and it can close prematurely.

The second method is more reliable for fixed length packets, but will only work for a certain (or small range) of baud rates. If sending a packet takes longer than the allotted window then it will truncate regardless.

However if the controller in the servo is itself directly controlling the data direction pin then it could be that there is a bug in its firmware. Maybe it's working on a delay principle and they got the time calculations wrong.  Maybe it's working on a "queue being empty" principle and they forgot about there being a hardware buffer that also needs to empty, but high baud rates just manage to squeeze through in time.

It's impossible to be sure, but going by the symptoms you describe those seem to be the most logical scenarios.


Controlling a Stepper Motor - sending to specific positions on a 'buttonPushCounter ==' cue, forwards and backwards

Thanks. Your description of the fault makes sense to me. As you point out blocking would be a problem as I need the counter to continue to be registering while the movement is being executed. I've revised the script as you suggest - inside the loop but outside the if statement - have I done as you meant? But the same problem occurs - the motor advances in single steps.

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // save the current state as the last state, for next time through the loop
    lastButtonState = buttonState;

    if (buttonPushCounter == 10 ) {
      digitalWrite(ledPin, HIGH);
      Astepper1.moveTo(20000);
      Astepper1.setAcceleration(6000.0);
      Astepper1.setSpeed(600);
      //Astepper1.setSpeed(600);
      Astepper1.run();
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

    if (buttonPushCounter == 30) {
      digitalWrite(ledPin, LOW);
      Astepper1.moveTo(200);
      Astepper1.setSpeed(600);
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

  }


Why do I get access denied when I do have mysql root user added to grant all privileges?

I finally figured out

By default it may proabbly have an IP address 127.0.0.1 bind to the 3306 port . This won't let your Arduino Ethernet shield connect to mysql server running on a different machine. In my case, I have mysql server running on raspberry pi 3, and it has IP 192.168.1.145. So for arduino to push directly to databse on remote mysql server, you should have mysql server IP 192.168.145 bind to 3306 port of mysql server running on it. So that MySQL server is visible to remote client on local network on which your arduino Ethernet shield is connected to via LAN.
Then you login to mysql server , and create a user :

CREATE USER 'myuser'@'192.168.156' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then you grant privileges as shown below.

GRANT ALL ON *.* TO 'myuser'@'192.168.156';
GRANT ALL ON *.* TO 'myuser'@'%';

Important Note:  the ip address shown in above mysql queries 192.168.156 is the ip address of my ethernet client establishing connection with database on mysql remote server.

Thats it.


SdFat: Why does the first write to the file take so long?

Most file systems exhibit poor performance if you store many files in one directory. 'Normal' desktop computers are perhaps so fast, that you don't notice the performance impact, but accessing the file system from a relatively slow micro-controller, which also have limited means of caching the file system data structures in RAM, you may have to consider for this and either write a smaller number of files or build a tree of directories, so that you only have a limited number of files in each directory.


Atmega328p with arduino without the board

The board option is actually selecting a variant out of the installed cores (which provide the basic Arduino framework for a group of boards/chips). Each core can support multiple variants/boards/chips and can give each of them individual lists of options. There certainly also is a core, which supports the Atmega328p with all needed config options (like the frequency setting). You just need to install it from the boards manager.
Though, since you use a 16MHz crystal just like the Uno/Nano, you could just select the Uno or Nano as board. Neither the Arduino IDE, nor the Atmega328p can know, that the Atmega is actually a standalone one and not mounted on an Arduino board. So you can just use that board when you keep the config options inherent to an Arduino Uno/Nano (frequency setting and pin mapping mainly).


Bidirectional communication between Arduino and Raspberry Pi over USB possible?

Yes.  The Arduino Uno implements a serial protocol inside the USB signal using hardware.  This is how it is built.  The Linux side is a bit more complex as there are many USB protocols.  Here is a howto which talks about the Linux side of the Arduino / Linux connection.

To be clear, Rasbian is a derivative of Linux.


How to delegate code compilation to a remote machine?

If you don't have a GUI, you can still compile and upload sketches by using the Arduino CLI. With it you can do most things, that you can do with the Arduino IDE. I'm using this myself to upload new code to a Nano, that is connected to a Raspberry Pi in a project in use.

You can connect via ssh to the remote server and let it compile/upload the sketch. I wrote a simple bash script to first copy the source to the server (since you are using a network share, this is not necessary for you) and invoke the compilation and upload.

Note: Before you can actually compile with the Arduino CLI, you have to download the correct core for your chip. This is described in the README of the linked github project.


The data sheet sample circuit shows either an open output (presumably into a high impedance input such as the '328's A/D), or connected to -Vs via a resistor chosen to draw 50 mA. Access to -Vs is not typical of our applications but they do show a current-limiting resistor to ground in that case. So I'd expect that grounding the output caused the device to draw more current than it could dissipate without overheating.


The usual "sketch" is "always" running on your arduino (Controllino) unless it is put into a non-run mode (like when loading a program) or doesn't have power.  What you need in your sketch is to do something IF a command is received on the serial (RS485).  Rather than simply running the command you want, the sketch needs to check the serial and only execute the command if the HMI sent the correct signal.

For motor control, you could use G-code where your HMI sends G-code move commands over RS485 and your Controllino executes them.  A handy RS232 example is grbl.


Why is there already text in the serial monitor before the Arduino initializes?

It's because the Arduino has started running the sketch and placed data into the USB chip's buffer. You then open the serial monitor which then opens the serial port thus resetting the Arduino. So the sketch runs again.

It only resets the Arduino, not the USB interface chip, so you get what was in there from the first execution plus the new text from the second (post-opening) execution.

You cannot "avoid" the extra bytes, that's just the way things are. The Arduino resets. There are buffers in various places. You have no control over those buffers.

As a side note: the serial monitor is completely disgusting. If you want to do things properly use a proper terminal emulator, then you can use ANSI control codes to do things like clear the screen, move the cursor around, apply colour, etc.


Arduino not running code without connection to PC via USB

Have you made sure that the ground of both the arduino as well as esp8266 are connected together? Also since you are using esp8266 you must have connected it to rx and tx pins. Make sure you remove it while uploading the code and connect it afterwards.


Control RGB led using microphones, getting the right components

It would be worth checking out the ColorChord project.  It runs on an ESP8266, not an Arduino, but it ought to get you going.


Have you checked that MMA_7455 can handle this many reads?
I had sensors that stop working because I asked to often for feedback.
As the servo needs a 20ms to adjust its location I would add a delay(20) to the loop.


I want a couple of servos to listen for P.C. input (data from OSC protocol), can I bypass having to use an Arduino?

If I understand your question correctly you're asking if you can control servos with OSC and no microcontroller.
OSC is a protocol used for networking and communication between synthesizers, similar to midi in that, but totally different in the way OSC sends data which looks a bit like XML.
There's a couple of problems here:
1. Servos will not respond to OSC-signals. You could use MAX/MSP to generate servo-pulses from the OSC. The problem arises whan you are going to send this to the servos using usb.
2. USB, a fast data-transmission technology, is not suitable to be connected straight into a servomotor.

Arduino uses an atmega16u to transform the data from usb to serial (called a usb to serial programmer) for programming and communication. Then the microcontroller (atmega168/328) takes this and creates a pulse and a signal for the servo-motors.

To control servos without a micro-controller using USB is impossible.

It is be possible to control electronics using the serial-port and low-level coding. Used to do stuff like that on a Commodore 64 a time ago. Before these affordable, stable, reliable avr, arm and pic programming cards came out.

A tip: It is possible to load a program onto an atmega168/328 using a Arduino UNO or similar. Take the chip off of the programming card(ie. the Arduino UNO) and create a stripped down version, containing the micro-controller chip, 16kHz crystal, some capacitors and an usb to serial converter/ftdi-cable.

Regards
Krister Borge


If my understanding is correct, the flex sensor was connected between 5V and GND.
This acted like "short circuit" and should not have burned the AVR, but only the power supply side. If you have a multimeter and some soldering skills it should be possible to fix the board.

Supposing you have an genuine arduino UNO, here is a schematic but it may not be the right version

Remove the MCU
Check voltage between GND and XUSB is 5V (if not either your USB port is burned or you have a short on the board or a component)
Check voltage between GND and USBVCC is 5V (if not, replace the fuse)
Check voltage between GND and +5V is 5V (if it's still 1.5V as you mentioned, try replacing transistor T1 but I do not understand why it would burn. If it's 5V replace the MCU)

EDIT for Arduino Nano

I did not understand you had a nano board (schematic)

The component "B2" you mention is the diode D1 (MBR0520). It burned because of the short circuit you created and nothing else should be defect. It acted like a fuse. Simply replace it and it should be fine.

If you are VERY CAREFULL not to overload the nano with external circuitery and never bring external 5V you could just remove it and make a little solder bridge (waiting for replacement part)


Drive a 12V pump do I need a l293 driver

Unless you wish to reverse the direction of the pump without reconnecting the wires in the opposite way, there is no need for a L293. A MOSFET that operates as a switch should be sufficient in your case. You can also try to PWM it and reduce/control the water flow.


Apparently you can have an ad-hoc network, you can see the example on the github here:
https://github.com/arduino-libraries/WiFi101/blob/master/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino

It shows how to create an open ad-hoc network, for a secured one, you might need to check the datasheet + the method implement "beginAP".


Can I program a 3.3v chip on a 5v board?

The clock speed selected will affect both delay*() and millis()/micros() as well as the functions in <util/delay.h>, therefore you must use the target system's correct clock speed if you are using any of these functions. This can be easily done by editing boards.txt and copying an existing entry for the Uno and changing the value of the f_cpu parameter to match the target system (in this case, 12000000).

The difference in voltage does not matter, since the chip can run at either voltage and no connection is being made between the 5V system and the 3.3V system.


Program button to switch between two values

Pseudocode:

value = 0
if button is pressed:
  value = 1 - value


Can I write to Flash Memory using PROGMEM?

The short answer is no: PROGMEM data is read-only.

Flash memory limitations
The first thing to understand is that Flash memory (where program space lives) is designed for long-term fixed storage. Reading from it is very fast and precise. However, generally speaking, you can't modify it on a byte-by-byte basis (e.g. changing a specific variable). You usually have to erase and re-write it in large blocks. That makes it completely impractical for run-time manipulation, because you'd have to store a lot of redundant information somewhere else while you do the erase and write cycle.

What PROGMEM actually does
Any literal data specified in your code (such as strings and numbers) always reside in program space at first (i.e. in Flash). However, when your sketch actually wants to use that data at runtime, it normally has to allocate some space for it in SRAM and copy it over. That means you end up with two copies: the fixed original in Flash, and the temporary copy in SRAM.

When you use the PROGMEM modifier, you're telling it not to make that second copy in SRAM. Instead, your sketch will simply access the original in Flash. That's very useful if you only ever have to read the data, as it avoids the allocation and copy operations.

However, copying it to SRAM is essential if you want to modify the data. Aside from the Flash limitations I mentioned above, it's also a question of code safety.

If you're able to modify the data stored in program space, then it follows logically that you could also modify the code stored in program space. That would mean that a simple mistake (or in theory a malicious attack) could result in your sketch being partially or fully rewritten at run-time. This could have very unpredictable results, ranging from simply ceasing to work, through to damaging/destroying any connected equipment.

More information
You can learn more about the low-level PROGMEM stuff from here:

http://www.fourwalledcubicle.com/AVRArticles.php

An older version of the same PROGMEM tutorial is available here:

http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&p=243018


Lua, like many scripting languages, tends to make you a lot more
productive as a programmer: things become far easier as you work at a
higher abstraction level and do not worry about trivial things like
memory management. You achieve the same goals with far less lines of
code. On the other hand, whereas it makes development faster, it also
makes program execution slower. Whether this is a good trade-off or not
is very dependent on the particular application you want to write.

In your particular case, you also have to consider the fact that you do
not know Lua, and you already know both the C++ language and the Arduino
API. Then you may not rip the benefits of Lua on a single project,
because of the time needed to learn the language. You may consider
learning the language as an investment, probably worth it if you are
going to program a lot on this platform, probably not worth it if it's
only for a single, simple enough project. If unsure, I suggest you take
a look at the API provided with Lua on this platform: how well does it
fit your project? Is it a significantly better fit than the Arduino API?


Consider the following:
char buffer2[16];  // array of 16 chars
for (uint8_t i = 0; i < 16; i++) {
    do_something_with(buffer2[i]);  // handle one char at a time
}

Here we have an array of 16 cells, each having the char type (which I
assume is what you have). The loop goes through the array, handling one
cell a time. Within the loop, buffer2[i] represents the char being
currently handled.
Keep in mind that a char is just an 8-bit integer. It is somehow
implied that it is meant to represent a character, where 32 = ' '
(space), 33 = '!', 48 = '0', 65 = 'A' and so on (see ASCII).
The Arduino print() methods do assume a char (unlike an int) is
intended to be displayed as a character.
Now your actual loop:
int Item_Name;
for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i]);  // write the char on the serial port
    lcd.write(buffer2[i]);     // write the char on the LCD
    Item_Name=buffer2[i];      // store the char in a variable
}

This will print the contents of the buffer to both the serial port and
the LCD. You would have seen the expected message on the LCD if you did
not have lcd.clear() right after the loop.
sscanf(buffer2, "%s", &Item_Name);

This means “extract from buffer2 a sequence of contiguous
non-white-space characters, and store it in memory at the address of the
variable ItemName”. If the buffer contains “Fresh Milk 1Lt”, this will
write “Fresh” to that memory location. That is 6 bytes (5 letters and a
terminating NUL). Unfortunately, the compiler has only allocated 2 or
4 bytes of RAM for storing ItemName (depending on the Arduino model),
so this will write past the allocated storage, which is a type of bug
known as buffer overflow. Now your Arduino's memory is corrupted and
anything can happen.
sprintf(buffer2, "%d", &Item_Name);

This tries to find within byffer2 a textual representation of a
number, and store it into Item_Name. This is safe, but only makes
sense if the buffer contains a number, written as text, which is not the
case here.
lcd.print(Item_Name);

This is asking the LCD to print an integer (namely Item_Name). It will
convert the integer to decimal text and print the corresponding digits
on the LCD.
Let's assume for example that Item_Name contains the numeric value
32 (which is the ASCII representation of a space). lcd.print() will
convert that into a sequence of two characters: '3' and '2' (the
decimal representation of 32). It will then send those characters to the
LCD (ASCII values 51 and 50), and you will see the text “32”.
If you want to see the text contained within the buffer, the you can
either send the characters one by one (like you already did right before
lcd.clear()), or provide to lcd.print() a char* pointer with the
whole message:
lcd.print(buffer2);

This assumes that the buffer is terminated with a NUL character. If it
is not, then you can either use the char-at-a-time method, or change
your code in order to put a NUL terminator in the buffer.


if I add a .cpp file, Serial becomes unusable

A CPP file isn't an Arduino file. It doesn't know about anything Arduino-esque unless you tell it about it.
The simplest way is to just add, at the top of the file:
#include <Arduino.h>


Is a variable declaration inside a loop static declaration or dynamic?

It will be created every iteration.

Assuming, you are not using it to add to a list (e.g. to use in later loops), what you better can do is make it in a global, you also don't need to use 'new', thus:

Object object;

Also, if you do not delete/remove the object at the end of each while condition (with the delete keyword), you will lose the memory (and this is a memory leak). Also, you run the risk of memory shortage (the Uno has only a few KB of memory).

What I also miss in your code is the pointer (*, because the new keyword creates a pointer), and also Obj and Object are inconsistent types (they should be equal), so:

Object* object = new Object();

If you only need the object within the condition and it can be removed in the next while, than you don't need to use new, so just declare it as a vaiable

Object object;

This also has the benefit that the (local) variable will be destroyed at the end of scope (which is at the end of the while).


Arduino code won't upload with Ethernet Shield attached

The Ethernet Shield uses the pins  D10, D11, D12 and D13 on the Arduino UNO. I presume there is a conflict and you use one or more of these digital pins in your setup already.

A nice overview of possible conflicts between shields and arduino boards can be found at:
http://playground.arduino.cc/Main/ShieldPinUsage


SSD1306 / U8glib display fonts and commands

First, u8glib is superceded by u8g2

Second, the u8glib wiki has a command reference and font reference.

As does the u8g2 wiki.

Neither reference lists a display() command.


Use a USB tester to test the current consumption, it should be < 500ma
I recommend using a USB that has power of its own, eg. monitor USB


Uno - PCA9685 Servos are too shaky before stabilizing - when using two channels

Start by verifying the power supply is adequate, then go from there. If nothing else try a much bigger capacitor.


Error: "'lcd' does not name a type" using LiquidCrystal library

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


Having used counterless Arduinos and clones, I can tell you that you can connect both without worrying about any danger. Unless you have a very faulty board, your pc won't be damaged, almost surely neither will the board, as is should select the most powerful source, between your usb or a battery/external PS, while leaving untouched the serial line.


Judging from the comments, you lag some basic knowledge. To really learn, what you are supposed to learn in this assignment, you should review your learning material or C/C++ and Arduino Tutorials on the web. Here I will only give you some hints with reasoning, that may help you in solving the assignments task. (Unfortunately it is not really clear, what exactly the task is here)

The Serial interface of the Arduino (an UART interface) sends the data in bytes, one at a time and one after another (hence the name serial). 1 byte is a series of 8 bits, each of them with a value of 1 or 0. Together the 8 bits form a value, that can also be expressed as a decimal value from 0 to 255. For example 01001011 is the binary equivalent of the decimal number 75. (For further explanations google the binary number system) The byte data can also be expressed as characters, as they are defined in the ASCII standard. Every binary value refers to a specific character. This is what happens in the serial monitor of the Arduino IDE. (For more explanations google ASCII)
Since the data is send serially, there may appear some delays in the transmission, which are unnoticeable by humans, but the Arduino is fast enough, so that the Serial.available() command may return 0, because at that moment a little delay in the transmission occurred. Hence it is important to catch the whole message, before trying to work with it. You can do this by either counting bytes (waiting until at least 3 bytes are available in the buffer) or by marking the end of the message with a special character (for example the newline character '\n'). There are a lot of tutorials on the web how to do both. You can start with Majenko's blog.
You can get the number of bytes, that were received, with the return value of Serial.available(). It will return 3, when there are 3 ready to be read bytes in the buffer.
If you define a variable inside the void loop(), it will be thrown away when the function ends and redefined, when the function starts again (In the Arduino world the void loop() function is called again and again forever). You will loose all content, that was written to this variable. If you want to persist data over the executions of the void loop() function, you can define the variable outside of any function at the top of your program. This variable is then global and will be defined only once at the start of the program and hold for the whole lifetime of the program.
As wrote in the comment you should not return a value from a void function, since void mostly means, that there is no return value. And returning from the void loop() function will only restart this function (since we are in the Arduino world).
You can ditch the delay(2). There is no need for it. And if it only works with the delay, then something else is not correct and you are just working with the symptoms instead with the real issue.

Also you should not try to build everything on your own and reinvent the wheel. Instead try to look at the examples, that come with the Arduino IDE. For example the SerialEvent example, which shows how to receive a serial message (which is ended by a newline character '\n'). Also have a look at the other related examples. If you understand, how they work, you will be able to do the assignment without any problem.


The struct is a declaration of a type. You cannot mix it with the initialization. This is how it could be:

In foo.h:

#ifndef FOO_H
#define FOO_H

struct Foo{
  int randInt;
};

extern struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr);
#endif

In foo.c:

#include "foo.h"

struct Foo foo;
struct Foo *initFoo(struct Foo *foo_ptr) {
  if (!foo_ptr)
    return NULL;
  foo_ptr->randInt = random(0, 101);
  return foo_ptr;
}

random() is a function and therefore its return value cannot be used as static initializer.
Unless -std=c++11 or -std=gnu++11 are enabled.


I'm not quite sure I understand the logic of what you're asking. Your description is a little vague. Maybe if you provided more information about what the signals are, what they mean, and where they come from, it may help.

However - if you want the melody to play when both inputs are LOW you should change:

if(StatOutDoor == LOW && StatInDoor = LOW){
      PlayMelody();
}

to:

if(StatOutDoor == LOW && StatInDoor == LOW){
      PlayMelody();
}

Note the use of == not = to denote equality (= is assignment).

Also the use of a 3.3 second delay in your else will show everything down to a crawl when StatInDoor is HIGH.


How can I send data to many IC's without using tons of shift registers?

There are other ways,but for a brute force many pin driver solution:

Back at the beginning of time when steam driven IC's were all the vogue there was the awesome MM5450.  40 pin DIP. 34 on/off outputs. 3 pin control. Or the really keen could do it with 1` pin control and some basic RC timing. I was. I did.

Its day has passed. but, fortunately. neither Micrel or Digikey know this.

MM5450 datasheet
In stock Digikey $5.46/1

It's a very benign beat to drive once you get to know it. There is no reset (inless you buy bare dies) so you have to start off getting it synchronised  - it's not hard, just not quite usual. Works well.

For single GPIO pin control the pin acts as data out and clock with some RC timing.
Fot ICs with clock/data/load you can do all 3 with RC timing on one pin.

And there is a 44 pin PLCC pkg version available.

AND!

SN74LS673 16 bit SR, 24 pins
http://www.ti.com/product/sn74ls673

ICM7243
http://www.ebay.com/itm/ICM7243BIPL-HARRIS-40-Pin-DIP-LED-DISPLAY-DRIVER-ICM7243-7243A-/390402848376

And others
http://www.ebay.tv/sch/i.html?_sop=7&_nkw=led+driver+ic&_frs=1


Firebase.failed() returns 0 after Firebase.begin(), but returns 1 while reading or writing from/to firebase from ESP8266

Apparently the Firebase's fingerprint has changed recently and has caused the above issue!

from here get the latest finger print and change it in the ...\Arduino\libraries\firebase-arduino-master\src\FirebaseHttpClient.h

In the file mentioned above: update the value of static const char kFirebaseFingerprint[] to the new one mentioned above.

P.S. One issue going forward for me(planing on implementing it on a long term basis) is how to be ahead of this issue in the future, so that I can get the data uninterrupted!


Have you used the pull-up resistors SCL and SDA need to be pull uped using 5V. Try this and check if it is working have you connected SCL to A5 and SDA to A4


Need to set an output pin without it going LOW during initalization

Arduino sketches are actually (somewhat constrained) C programs.  As such, what is true for C is usually true for sketches.  In C, a segment of code usually ends with a ";".  It matters not if there are two (or more) of these on a single line.  The computer will execute the segment before the first ";" first and the segment after the first ";" second.

In this case you are setting a register inside the Atmel processor on the Nano to the "out" direction.  So it will force the associated pin to what ever the data in already set up in that pin's data register.  Then you are setting that pin's data register to high or 1.

Instead, try setting the data register to 1 before setting the direction register to "out".  Do this by switching the order of the code segments.

In case this does not work.  Or in case you find the relays acting randomly on power up, consider the relay driver inputs to be high impedance and susceptible to any noise prior to the Nano taking control of the relay driver control pins.  In such a case, consider adding pull up resistors small enough to ensure the inputs of the relay drivers are held at a known voltage but high enough such that the Atmel processor in the Nano can easily over power the pull up resistor when necessary.


How to send data to multiple slave at a time

The I2C protocol implements the general call/broadcast address for this purpose. If you send data to the address 0 (zero), this is interpreted as general call by all slaves. All slaves, that can receive data, will respond by pulling the SDA line to low in the acknowledgement cycle (the timing is set up by the masters clock so all slaves will do it at the same time, thus no problem with garbled data). Note, that you cannot read from the general call address, since then all slaves might transmit at the same time. As the Atmega328Ps (the microcontroller on the Arduino Uno) datasheet states:

  Note that transmitting the general call address followed by a Read bit
  is meaningless, as this would cause contention if several slaves started transmitting different data.

I think the Wire library does not do any read operations on the general call address to prevent this, so this would not block up the I2C bus.

  how to check which slave has recieved the first

Not, because all slaves receive the data at the same time. The I2C bus is much like the IP protocol in this topic. A master/sender is sending out packages of data with the address of the intended target. But it is up to the slaves/receivers to decide, on which address they want to listen. So on every I2C transmission you are sending data over the bus, that could be read by all slaves. Only that in normal operation a slave will decide to only listen to the bus, when it sees it's own address (or the general call address).


You should not create the Ethernet server. The library creates the server and your server takes the port first.

Modbus function code to read Input registers is 04.


Did you add your libraries to the cmake files?

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

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


I was looking at WS2818B datasheet, they do not use i2c. It just needs a single ( dedicated) pin to receive the color/brightness commands.


Home made drum kit - How can I speed up the response time after my sensor gets triggered?

This is not really a 'solution', but it might help you in finding out where the real problem is.

Check out which of the statements in the loop function uses up the most time, probably;

int fsrADC = analogRead(FSR_PIN);
Serial.println(String(fsrADC));
snare_file = SD.open("606snare.wav");
while (snare_file.available()) {
snare_file.read(snare_buffer, 1024);
Audio.prepare(snare_buffer, 1024, 1024);
Audio.write(snare_buffer, 1024);
snare_file.close()

Try improving the most time consuming item if possible.

Some possibilities you can try in the steps above:

Do not use AnalogRead but direct port commands
Remove this completely or at least remove the String instance.
Not much you can do here, except not using a file system but raw SD read (you might have problems getting the files on your SD) without a dedicated program on your PC
Not sure about improving this one
Read less bytes, although it might even worsen things. Or read the bytes BEFORE waiting on the trigger (if you know which sample will be played).
Execute the prepare as before the trigger as 5 if possible.
Not sure about this... High likely you cannot keep too many files open at the same time.

Afaik in my synthesizer (Korg Kronos), it reads from all samples the initial part, meaning it can startup the data from RAM, while the rest is read through SSD (in your case SD). However, you might not have enough memory in an Arduino for that.


I fried my arduino. Can I upload code wirelessly?

If the main MCU is still functioning fine then yes, sure you can.

The only caveat is that you may have to manually reset the Arduino at the right moment in order to enter the bootloader for programming.

Connect the bluetooth module to TX/RX/GND (TX->RX, RX->TX)
Configure the bluetooth module to work at the bootloader baud rate (115200 baud) - you may need to wire it to your PC to manage this part.
Connect a virtual COM port to it and program through that.
Press RESET just as it's about to run AVRDUDE in the IDE.


Arduino Mega resets when DFPlayer speaker plugged into amp!

For externally amplified speakers, you should be feeding the DAC and GND pins to the amp's inputs.  Those DAC pins provide a signal that varies by a small number of volts and is shifted so that they're always positive.  This is in the range expected by small headphones (ear buds) and line level inputs to audio components like an amplifier.

The speaker pins on the DF Player mini are pre-amplified (a little tiny bit) to directly drive a very small speaker (like 2 Watts at 8 Ohms).  They are a differential signal that includes both positive and negative voltages (relative to GND).  Note that the two speaker outputs (SPK+ and SPK-) are not left and right, but two sides of a differential signal.  Based on the schematic on page 11 of the datasheet (Chinese), it's a mono output made from mixing the outputs of the left and right DACs.

I could see how you might have gotten away with sending those to the amp, since the pre-amped speaker outputs are low power, and a good amp probably has input protection.

I don't know enough about electronics to know why it's failing now when it seemed to be working before.  It could be sensitive to the amplifier's gain or a ground loop between the power sources, but I'm just shooting in the dark.  Somehow, I suspect the DF Player Mini struggled to provide enough current to your amp, and since the DF Player Mini was powered from your Arduino, the Arduino essentially browned out, triggering a reset.


Use Wire.print(), instead of Wire.write() which is intended only to output single bytes or byte arrays.


Minimum circuitry required to program an AVR

I have a page about a minimal board. The minimal circuit is the chip itself, and a couple of decoupling capacitors. A pull-up on /RESET is advisable (however the processor has a weak pull-up on it).

The six wires you mention are required for ICSP programming. An example from my page is:

That is using an Arduino as an ICSP programmer.

I think most designers would mandate the decoupling capacitors. You may get away without the pull-up on /RESET but probably at the expense of reliability.

The wires changed colour between the two photos because my earlier board (shown second) had the capacitors further away from the chip pins than they should have been. They really should be next to the chip for maximum effectiveness.

Note that, depending on the fuses, you may need to supply an external clock. In my case I did it like this:

The default chip fuses (from the manufacturer) does not require a crystal.


Is there an Arduino library that uses ARP to get list of connected devices on network?

ARP isn't generally used the way you described. Per the spec, to resolve an IP address into a MAC address, you broadcast an ARP request for the IP address, and receive  a unicast response from the host whose address it is - not a router. It also only resolves a single IP address in one request; it doesn't return the contents of the entire ARP cache.

While you could potentially unicast ARP requests to a router, it's anybody's guess as to whether the router would respond - it's not required to. By spec only the computer who's IP address is being queried should respond - so a router should not unless you've sent it an ARP request for its IP address. You'd also have to send one request for each IP address in the range specified by the LAN's network mask.

You're better off using SNMP, if the router supports it. SNMP can read the router's entire ARP cache with very little overhead (and very few packet exchanges).

The are SNMP implementations for the ESP32 and ESP8266, but they're likely to be difficult to use. Googling will find them for you.


GPIO12 must not be pulled high during boot. It's possible there's a pull-up resistor on the BME680 breakout board you're using that's pulling SCK high and interfering with the boot process. I would avoid using GPIO12 here.

If you're out of pins on the ESP32 you can connect the BME680 via I2C rather than SPI. I2C only needs SDA and SCK (and power and ground, of course). The Adafruit library for the BME680 has an example of how to call the constructor for an I2C connection.


Why isn't ESP8266 connecting to wifi when calling yield()?

Insert refTime = millis(); inside while loop.


Which Datasheet applies to the ATmega328p?

You have ATmega328P-AU. Classic Uno with DIP socket has ATmega328P-PU. Arduino Uno SMD has Atmega328P-MU.

The automotive versions ATmega328P-15AZ and ATmega328P-15MZ have separate datasheet starting in Revision History with

  Creation of the automotive version starting from industrial version
  based on the ATmega48P/88P/168P/328P datasheet 8025F-AVR-08/08.
  Temperature and voltage ranges reflecting automotive requirements.


How many Amps can a Nano Arduino hold for LED project

Yes, 120 LEDs * 60 mA = 7200 mA = 7.2A

An Arduino Nano will use 19 mA (Arduino Nano Tech Spec). Of course, if you add a power LED, or other components it will add, but it will likely be less than a few 100 mA. So that totals to max 7.4A.

It's always good to have some headroom which is 0.6A in your case (that's enough).

Actually what's happening is as follows:
- Your 8 mA gives the current the components request
- Your Nano requests 19 mA
- Your LEDs require 7.200 mA.

As long as the voltage is the same (5V for both the LEDs, Nano, and adapter), and the components do not request more than 8 A summed up (with some headroom), the adapter will deliver the current needed. If all components request more than 8 A, than high likely the adapter will break (and possibly the attached components too).


To connect a simple toy circuit and trigger with an arduino?

You'll probably want to use a transistor to switch it on/off. You could just use the Arduino's digital pin but they can only supply a limited amount of current. Transistors can work with larger currents. The Arduino switches the transistor and it powers the external circuit.

There are a couple of existing questions that may help you.

How to switch an external circuit with Arduino?
How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?

jippie's answer in the first link shows an example schematic for hooking up a transistor with a bunch of LEDs but you would replace them with your own circuit:


Testing Arduino with Visual Studio Community 2013 raise LNK error

I use Visual Studio Community Edition 2013 along with the Visual Micro extensions, which I think is what you need as the "missing link" between VS and Arduino.


How to build a valid HTTP Response. Recv failure: Connection reset by peer

HTTP requires an empty line after HTTP headers.

First line is status line. Then the header lines. The headers are terminated by an empty line. Then the response body follows. Line terminator for HTTP is \r\n. Arduino println() function uses \r\n.

The response with body should contain Content-type and Content-length header. Alternative to Content-lenght is "chunked" Transfer-Encoding.

ESP8266WebServer library handles HTTP for you.


Can I get around extremely long time to setup WIFI connection WPA2 Personal?

4 even 5 seconds is normal for connecting to WiFi. How long takes your phone or other devices to connect?

You can connect a little faster with static IP address.

EDIT: With WiFiNINA library for Uno WiFi Rev.2, you can change the connection timeout with WiFi.setTimeout(). The default is 5 seconds. WiFi.begin() can end with WL_CONNECT_FAILED but if you later check the status of the connection it will eventually be connected.

With esp8266 or esp32 you can make the connection persistent and it is build up immediately after boot and asynchronously. WiFiNINA library doesn't make this possible yet. Some future version will offer WiFi provisioning.


The layout of that library is in a non-standard format with folders that UECIDE doesn't know to look for or how to deal with.

The main culpret is the inclusion of big chunks of code in a "clib" directory (why on earth?!?!) which doesn't get included in the compilation. Then on top of that you have header files in there that are referenced both from inside it and outside it.

The simplest fix is just to copy and move the files to better locations:

$ cd ~/Documents/UECIDE/libraries/U8g2/src
$ mv clib/*.c .
$ cp clib/*.h .

Note you move the source, but copy the headers. That's to get around the problem of the headers being referenced from two locations with relative paths.

The problem stems from UECIDE having (by necessity) much stricter rules than the Arduino IDE over the layout of a library. This is to facilitate better identification and categorization of the libraries so that recursive dependency detection can take place.


It depends on your need:

1. No other activities / main power

If during those 30 minutes (I guess), the MCU does not have to do anything else (except maybe handling some short interrupts), than you can use a delay. You can use this if your power source is an adapter, but you waste a lot.

Advantage: Easy to program
Disadvantage: Power will continue to be used.

2. No other activities / battery

If you have the same conditions as above, but using a battery, than as Juraj mention, use the sleep functionality of the Arduino. You need an (external) real time clock or other circuitry to activate the wakeup signal after 30 minutes.

Advantage: Very less power used during the 30 minute delay
Disadvantage: Slightly more programming

3. Other activities

If you want to do now (or later) other code to be executed during the 30 minute wait, use millis(). For example, when you want to extend your project using other libraries that needs a faster than 30 minute response.

Advantage: You can do other tasks meanwhile
Disadvantage: More power usage, slightly more programming


How to pass JsonObject from ArduinoJson to ESP8266WebServer object?

As far as I know, the only way is to serialize the JsonObject to a String:

String createJsonResponse() {
  StaticJsonBuffer<500> jsonBuffer;

  JsonObject &root = jsonBuffer.createObject();
  JsonArray &tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray &humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray &dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray &EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);

  String json;
  root.prettyPrintTo(json);
  return json;
}

void outputJson() {
    server.send(200, "text/json", createJsonResponse());
}

By the way, I recommend that you use the ArduinoJson Assistant to compute the size of the JsonBuffer.


All bluetooth modules will need some sort of mcu to handle the requirements of the protocol stack, and it seems common that there will be at least a couple of GPIO which can be used directly if your sensor requirements are simple. At the other end of the spectrum, you will find there are also mcus with a full set of peripherals - enough to support a couple of sensors and a small display for example. Remember, the wearables market is likely bigger than the hobby electronics market.

Limitations are most likely to be in the area of ease of use (as you hint at with your question), and possibly the toolchain which you would need to use (unlikely to be arduino compatible). Also, the bluetooth stack typically takes a reasonable proportion of these wearables focused devices, so there is not a big amount of ram/flash or CPU cycles to spare even if you opt for a part which is more than 'just' a serial-to-bluetooth bridge.


ESP8266WebServer how to parse Json payload in post request that is bigger than the ram

The ESP8266WebServer library can process only a HTML-Form POST request of application/x-www-form-urlencoded or mulripart/ content type.

You could sent the JSON as multipart 'upload' to save it to file, but it would require to build the multipart format of the POST body.

If you want to process POST with application/json content type, you could make a simple web server implemented with WiFiServer.


You could do what you want as you describe it, but are making things harder for yourself that you need to. If you can access the circuit from the switch at or near the switch (which should be 'easy' in most cases) then your system does not have to be depowered when the lighting circuit is as you will have access to the mains AC voltage on either side of the switch.

If you do wish to depower the processor when the lights are turned off you can easily add either a backup battery or a capacitor that runs the processor for "long enough". You can also run a processor in "sleep" mode at extremely low power so that it is always running so have no 'wakeup time". And it is possible to power up a processor so that the delay is not noticeable for practical purposes.

However, as Hue Bulbs are Zigbee controlled, with provision ofr both iOS and Android control,  you should be able to control them via Zigbee directly without any connection to their wiring.

Hue control

Hue specifications


What is difference between analog and digital input and output, and when should i use anlog or digital (input or output)?

You will use digital pin modes when dealing with signals that are either "on" or "off", such as an LED, a switch, or another digital IC.

Analog inputs are used when you want to read the voltage potential of something. This is typically used to read analog sensors. Analog outputs are not really analog at all on the Arduino. Instead, the Arduino uses something called PWM to create a pseudo-analog signal.

You can read more about analog and digital here:
https://learn.sparkfun.com/tutorials/analog-vs-digital


Is it possible to connect NRF24L01 to localhost in laptop without wifi router?

It is possible to have 2 NRF24L01 radios to talk to each other without a WIFI router.

However, is it possible to get your notebook to talk to a NRF24L01?  Probably not unless you can write a device driver for it.

You could use two Arduinos each with a NRF24L01, and get one to receive the data and then send it via Serial to you laptop, but you would be better looking at an ESP8266, set that up as an access point, connect your laptop to that network and job done.

(By the way you won't be able to call you laptop localhost)


Purpose of this resistor in Arduino Nano schematic

The resistor is one of 4 resistors that make up an SMD resistor array, RP2. It is seen on the board here:

The resistor array works like this:

The resistor on this array is spare, so both terminals are grounded.


It's parsing a bunch of semi-colon separated data, like "12;34;45;". In each iteration, it converts one value from character representation to its integer value.
strtok_r is the reentrant version of strtok. On Arduino you simply use strtok. Every time you have to parse a string having a list of values separated by some char, you use strtok.
Name
strtok, strtok_r - extract tokens from strings
Synopsis
#include <string.h>

char *strtok(char *str, const char *delim);

char *strtok_r(char *str, const char *delim, char **saveptr);

The strtok() function parses a string into a sequence of tokens (sub-strings). On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.
Each call to strtok() returns a pointer to a null-terminated string containing the next token. This token does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.


Can an IC be programmed by an Arduino and then be removed, to be used in an external breadboard?

Yes. The compiles code will is burned in the Arduino ROM. You can then take the Atmel chip (the Arduino microprocessor) and use it. You only need a few extra component for a chip like the 328p (Arduino Uno).


Question is - do I have to have two power supplies?

No, you can use one power supply for both. But you need to make sure, that the LED current is not flowing through the Arduino, since that can kill the Arduino. To do that, you need to connect the power supply to the LED driver and the Arduino in parallel. For example, lets assume you have bought a 5V wallwart/power supply, which is can provide enough current for your whole circuit (and some headroom for further development). Then you can connect the positive lead to the 5V pin of the Arduino and the Vin+ (positive supply voltage) pin of the LED driver. Also connect the negative lead of the power supply to ground on Arduino and Vin- (negative supply voltage) of the LED driver. That way the current for the LEDs comes directly from the power supply and doesn't need to flow through the Arduino, but past it.


According to the datasheet you have to calibrate it.


You have two issues going on - noise pickup, and a potentiometer with imprecise stops at one or both ends.

The pot is the easiest to fix: What are the lowest low reading and highest high reading you can reliably get when you turn it to its stops? Use those in place of '0' and '1023' in your map() function.

Improving the noise is only slightly more involved. An exponential average is an easy filter to write and quite effective at quieting noisy data, as long the signal to noise ratio is fairly low. The basic idea is you add only a fraction of each new value and keep (1 - that fraction) of the old average; so if your chosen fraction is 0.1, you only consider 10% each new datum, keeping 90% of the current average.

avg = f*avg + (1-f)*new_value

The output of this averaging filter can be slow to respond to changes if your fraction is too small, but less effective at quieting noise if your fraction is too large.

I usually use .25, or 25% of each new point and 75% of the current average, when I'm just trying to clean up minor noise, which is what you probably have.

Here is my 25% averaging filter:

int16_t xpavg(int16_t newdat, int16_t avg){

   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}

As you can see, I do the arithmetic in Fixed Point - just like integer arithmetic, but with an assumed binary point 2 places to the left during the computation. And I choose a fraction that represents "nicely" in binary - 1/4 in this case - to keep the arithmetic faster (since multiplication and division can be replaced by shifting).

The function just multiplies the current average by 4 and subtracts the old average (effectively multiplying by 3), adds the new value, and divides the sum by 4. (That extra "+2" rounds the fractional bits just before we shift them away). The end result is: (3*avg + newData)/4 (== 3/4*avg + 1/4*newData).

If you were to only sample the pot every second or two, you could probably observe the delay as the filter falls behind while you turn the pot and catches up when you stop. If you're sampling at 10x/sec or less, you shouldn't be able to notice.

Update:

You need to add the function xpavg() to your code, and call it each time you read a new pot value (that is "newdat"), passing it the old average as well. It returns a new average pot value, now less affected by noise. You use that new average value instead of the raw number you just read from the pot, in your hue calculation. As Duncan offered, you can - and I do - initialize the average with a raw value from the pot. You could also start it at zero but it will take a few samples to converge on the current actual pot reading. The downside of using one raw sample to start it is that if that one value is terribly noisy, i.e. way different from the pot reading, it will still take a few samples to converge.

unsigned int AvgPot = analogRead(poti1);        // initialize pot average

// Exponential averaging functions
int16_t xpavg(int16_t newdat, int16_t avg)
{
   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}

void setup()
{
   ;    // initializations go here
}

void loop()
{
   int hue = analogRead(poti1);
   hue = xpavg(poti1, PotAvg);
   int mappedHue = map(hue, 0, 1023, 0, 65535);

   neoPixelStrip.fill(neoPixelStrip.gamma32(neoPixelStrip.ColorHSV(mappedHue, 255, 255)));
   neoPixelStrip.show();
}


Your android app might be sending extra characters like "end of line", which will cause the return value of Serial.read() to be other than 1 or 0 after the first byte. Nevertheless, it looks like it should still turn on or off the LED as soon as it reads the first byte, and do nothing when it reads the following bytes. I have used the "hyperterminal rs232" app successfully to send single characters, maybe give that I try to see if it helps and ensure it is configured at the correct baud rate.

I would recommend to send back to the serial stream the characters read, to ensure they have been received correctly, so I would change this:

if(Serial.available() >0)
{
    state = Serial.read();
    flag=0;
}

to:

if(Serial.available() >0)
{
    state = Serial.read();
    Serial.print(state);
    flag=0;
}

Edit:

Just realised this in setup():

digitalWrite(0,HIGH);

You are setting the receive pin of the UART peripheral to hight, so that is probably why you are not reading data from your phone.


It is not possible to set the bootloader space to 0, but it is possible to unlock the bootloader space entirely by unprogramming the lock bits as well as to enable normal booting by unprogramming BOOTRST in the high fuse byte. Access to the entire chip will then be fully unrestricted.


New to Arduino: Should I learn C, C++ or both (C & C++)?

The basic syntax of C and C++ is very similar, to the point that C code can typically be compiled directly as C++. You'll also find C standard functions (such as printf and malloc) can be used from C++ programs.

The major difference in the core language is that C++ has a lot of extra stuff such as classes and templates. Conventionally, C++ also has a huge standard library which doesn't work on C. However, that's not usually available (nor really appropriate) for Arduino programming, so you don't need to worry too much about it unless you migrate to e.g. desktop programming.

Basically, it's probably sensible to learn C first, because the same knowledge works in C++. You can then move on to the C++-specific stuff, such as classes.

As a side note, the Gnu Compiler Collection (GCC) actually covers both C and C++. It's what the Arduino IDE at Atmel Studio use under-the-hood for all their compilation. It's even possible to work directly with GCC but still upload programs to Arduino via USB.

It's also worth noting that programs compiled within the Arduino IDE aren't necessarily going to run any slower than programs compiled some other way (whether C or C++). The main difference is whether or not you use the Arduino functions. Since they are general purpose, they're not necessarily doing things the most optimal way. You could get more efficiency in theory by manipulating the microcontroller's special registers directly, which is you can do from within the Arduino IDE as well. It's usually very tricky for a beginner though, so it's probably not something you want to attempt until you're more comfortable with C/C++.


How to precisely control servo motor by changing duty cycle?

The best is to use 10us Period, instead of 50us.
That precision will be close to 1°


You can use a number of Wire.write to write data.
The AD5694R should get three bytes and two bytes can be read from it. There is a "multiple dac readback sequence", but that is an extra.

Your AddressWrite requires an extra Wire.write.
Your AddressRead is missing a Wire.endTransmission and the while(!Wire.available()) should be removed.

void AddressWrite (byte Naslov, uint16_t Cifra1)
{
  byte Hi, Lo;
  Hi = highByte(Cifra1);
  Lo = lowByte(Cifra1);

  Wire.beginTransmission(Address);
  Wire.write(Naslov);       // command byte
  Wire.write(Hi);           // msb first
  Wire.write(Lo);           // lsb second
  Wire.endTransmission();
}

uint16_t AddressRead (byte naslov)
{
  Wire.beginTransmission(Address);
  Wire.write(naslov);       // command byte
  Wire.endTransmission(false);  // repeated start

  uint16_t hi, lo, result;
  Wire.requestFrom(Address,2);
  hi = Wire.read();
  lo = Wire.read();
  result = word(hi,lo);
  return result;
}

I have added a repeated start, because that is according to the datasheet.

Could you make the names more according to the datasheet ? For example 'command' or 'commandByte' instead of 'Naslow'. And perhaps better names for the functions, for example 'writeAD5694R' instead of 'AddressWrite'.


Arduino motor shield will only work in one direction

I think you may be having an issue with how you are powering the shield.  Are you trying to do it with just your USB connection?

In your photo, I do not see a connection to your Arduino's barrel jack or to the Vin connector of the shield itself.  According to the SparkFun site:

  The Ardumoto Shield should be powered through one of two power supply inputs. Pick one or the other:

  The barrel jack input on the Arduino.
  The Vin input on the shield

  If you don’t want to use the Arduino’s barrel jack input, you can use the Vin input on the shield instead. This voltage input will supply both the shield and the Arduino. Like the motor outputs, this connection is broken out to both a 3.5mm screw terminal and a 0.1"-pitch header.

  Do not supply power to both the Arduino barrel jack input and Vin on the shield!

I hope this helps!

EDIT BASED ON COMMENTS
Since you are properly powering the shield, I would recommend the following (see the shield's schematic for specifics):

Maintaining the connection shown above (with the addition of the 9V power supply connected to the barrel jack) ensure that you are able to properly set the DIRA input.  You can check this with a multimeter on pin 7 of the LN298 whenever you are trying to switch directions.
If you are getting the expected results on pin 7 (pin goes HI when your code wants the motor to go one direction and pin goes LOW for the other) - check pin 9... the value here should always be the opposite of what you are setting for DIRA on pin 7.  If that is all good, then you probably have an issue with the LN298.
If you are not getting the expected results at pin 9, but pin 7 looks good, then you are having a problem with the 74HC1G04 IC (although I would doubt this since you are having problems with both the A and B motor outputs).
If you are not getting the expected results at pin 7, then double check the code to make sure you have set and cleared the correct output pin.  I would also check the solder joints of the connectors on the shield - you can set a multimeter to do a resistance check from the shield's connector (pin 12) to the direction input on the LN298 (pin 7).  If the continuity is measuring close to 0 ohms then there is probably an issue with your code.
If your code looks good, I have also had issues with bad outputs on the Arduino - you can check to see if you are properly toggling the direction pin (pin 12) on the Arduino without the shield connected.  Then, if the pin is not toggling, there is probably an issue with your Arduino - try toggling a different (unused) pin and jumpering it.


Can I connect a PWM pin on one Arduino to an analog input on another?

Yes, you can do this with "a little programming"  or more easily by adding two cheap components.

If you connect a say 47k resistor from PWM_Out to Analog_In and a say 100 uF capacitor from Anaolg_In to ground you will be able to read the equivalent analog value to an accuracy of around 1%. Read it N times (maybe 10 times) with a delay of say 12 ms between reads and average it for a better result. This works because the PWM period is about 1 mS so delaying for a period of multiple cycles but not an exact multiple means you sample semi randomly.

For the sort of resolution that you want (4 levels) a MUCH smaller capacitor could be used (maybe 1 uF.) But even a 100 uF capacitor is cheap.

You could instead use PWM out (analogWrite) and a digitalRead.
Perform say 100 digital reads with say 12 ms between reads (so about 1.2 seconds total) and keep two counts - PinWasHigh and PinWasLow for (obviously) high or low conditions. The contents of PinWasHigh tells you what % of reads was high. Due to random sampling you cannot rely on this for 100 levels but determining say 10 levels should give good accuracy. The sum of PinWasHigh and PinWasLow should total 100 as a sanity check.

While use of a serial port (hardware or software) or SPI allows more data transfer per time and without much effort, this simple analog method is good enough for many applications.


Else Statement Never Functions As Expected

7<count<15 is interpreted as (7<count)<15.  7<count will result in a false or true, which will be interpreted as 0 and 1 when later involved in the < 15 part of the expression, which means 7<count<15 is always true.
What you're probably looking for is 7 < count && count < 15.


Can the Mouse library scroll horizontally?

As suggested in the comments, I edited the core libraries to achieve this.

I'm using PlatformIO, so the library files I needed to edit were here:

~/.platformio/packages/framework-arduinoavr/libraries/Mouse/src/

And the required changes (to change a wheel parameter for horizontal (h) and vertical (v) scroll parameters were as follows:

Mouse.h

Change the declaration of move():

...
void move(signed char x, signed char y, signed char h = 0, signed char v = 0);
...

Mouse.cpp

Add the following to the report descriptor after the last INPUT message:

...
0x05, 0x0c,        //       USAGE PAGE (Consumer Devices)
0x0a, 0x38, 0x02,  //       USAGE (AC Pan)
0x15, 0x81,        //       LOGICAL_MINIMUM (-127)
0x25, 0x7f,        //       LOGICAL_MAXIMUM (127)
0x75, 0x08,        //       REPORT_SIZE (8)
0x95, 0x01,        //       REPORT_COUNT (1)
0x81, 0x06,        //       INPUT (Data, Var, Rel)
...

Change the definition of move():

void Mouse_::move(signed char x, signed char y, signed char h, signed char v)
{
    uint8_t m[5];
    m[0] = _buttons;
    m[1] = x;
    m[2] = y;
    m[3] = v;
    m[4] = h;
    HID().SendReport(1, m, 5);
}

The following terminal commands were also useful in testing these changes:

# List input devices
xinput --list

# List device capabilities
xinput --list <device-id>

# Watch for data sent from the device
watch -n 0.1 xinput query-state <device-id>


How does arduino fetch instruction string from sms and execute?

Your GSM shield will receive the SMS which your Arduino code can retrieve as a string of characters (that description hides a mountain of detail, most of which you won't need to know). It doesn't care what the content of the SMS message is.

Your Arduino code will have to translate from the message text to motor-control commands so you want some text commands that will be easy to parse, but not so trivial that any random message might wrongly be interpreted as legitimate commands.

The digit pair "15" might command motor 1 to speed 5. But you wouldn't want any message with a couple of digits in it to change a motor. (You didn't say you had multiple motors, and if not you can leave that part out).

Let's make the message distinctive enough that it's unlikely to appear in some other context, yet simple enough to distinguish as legitimate. It would be nice if it's simple to thumb-type, too!

"motor,1,5" could convey the same information as the "15" in our first example, doesn't limit you one-digit values, isn't likely to appear in a "Hey Dude, lunch at 12:15?" type of conversation, is easy to parse and isn't too long to type on a tiny keyboard. You could extend it later, so "motor,1,+2" could mean to increase motor 1's speed by two units, "motor,1,off" could mean power it down (not just zero speed), and "motor,all,off", well, that's probably obvious.

Look up the function sscanf() [oops: not sprintf()] for one way to parse the incoming strings and collect their data.

Update: sscanf() does the reverse of sprintf(): It reads a string, collects values from it, and assigns them to variables. Search sscanf on the web for a description of its use.
Here is a sample program that reads a few possible SMS messages, checks whether they are motor commands (according to my simple example SMS above), and if it is, assigns the contained values to some variables in your program. You can see by the return values of sscanf() whether and how many conversions it made from each message, thus your code can tell whether a received SMS looks like a motor command, as well as what the command values are:

/*
 * sscanf example - Uses sscanf to test and collect data from a
 * a command string.
 */

#include <WProgram.h>

void test_sscanf(const char *sms);

// Sample of SMS messages to test whether our sscanf() format string
// can recognize good ones and reject bad ones. Experiment by adding
// ones of your own:
const char *SMS[] =
{
   "motor,1,5",
   "Hello World,3,2",
   "motor 123 456",
   "moto, 7, 13",
   "motorized, 4, 11"
};

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

   delay(1000);     // delay for user to launch a terminal (if you're quick)

   // Test each SMS example in the SMS array
   for( uint8_t s = 0; s < sizeof(SMS)/sizeof(char *); ++s ){
      test_sscanf(SMS[s]);  // test one SMS string
   }
}

void loop() {
   ;            // nothing to do here
}

// Tests a sample SMS, prints the number of variables it assigned, and what
// their values were. '0' means it didn't assign any, probably because the
// command-word failed to match.
void test_sscanf(const char *sms)
{
   int16_t assigned, values[2];

   // Print the SMS and convert it.
   Serial.print("\nSMS: \""); Serial.print(sms); Serial.println("\"");
   assigned = sscanf(sms, "motor,%d,%d", &values[0], &values[1]);

   // Display the results
   Serial.print(assigned);  Serial.println(" values assigned"); // How many values? A good command has 2.
   if( assigned > 0 ){
      for( uint8_t i = 0; i < assigned; ++i){
     Serial.print("value["); Serial.print(i+1); Serial.print("] = "); // print each assigned value
     Serial.println(values[i]);
      }
   }
}


Your code is familiar to the process of calibrating ESC controllers and is common. As your code is correct, we have to look at the connections. How is arduino connected to the ESC controller? can you provide a diagram? Only GND and Pin 10 should be connected. Do not connect the 5V of arduino. Power up the ESC with an external source. I think ESC signal port is Hi impedance so it should be no need for any resistor. Take a look at this site: http://robots.dacloughb.com/project-2/esc-calibration-programming/

You can see in that picture ( and the picture on the link provided), only pwm pin and ground are connected to arduino. Show us your connections if things keep going wrong. Also, does your power source provides enough juice to the motor?


If you know that your while loop isn't working as expected, I'd instrument the while loop and see if it parses as you expect:

for (int i = 0; i < arraysize; i++) {
  while (file.available()) {
    character23 = file.read();
    if (character23 == '\n') break;
    if (character23 != '^') {
      content += character23;
    }
    Serial.print(i);
    Serial.print(':');
    Serial.print(character23);
    Serial.print(':');
    Serial.println(content);
  }
  content.trim();
  if (content != "") {
    result[i] = content;
    content = "";
  }
}

Are you certain it is working the first time?


Writing serial data, just once after read

When you enter a single character into the Serial Monitor and press Enter, three bytes are sent: the character, a carriage return, and a linefeed. Serial.read() only reads a single byte, so data is available three times.

Either loop reading until no more bytes are available, check for and discard any CRs and LFs, or use a serial terminal that doesn't require pressing Enter to send data.


What are these components in Arduino Mega Schematic?

The symbol indicates a pair of solder pads that can be bridged by the user using a blob of solder.

Here's something similar.

Figure 1. Source: CyberGibbons.


Serial Communication between 2 Arduinos for analogRead value

You'll want to get familiar with the standard C function sscanf().  It does exactly what you're looking for, converts an ASCII string into whatever type you like.

sscanf() API

The code to read an integer from the serial port would look something like this:

  char recv_buf[10];  int recv_int;
  Serial.readBytesUntil('\n', recv_buf, 9);
  recv_buf[9] = 0;  // make sure it's null terminated
  sscanf(recv_buf, "%d", &recv_int);
  Serial.print("I received: ");
  Serial.println(recv_int);


Streaming audio from PC to Arduino over WiFi

Well, a sort of... You can stream 64kbps MP3, get it via wifi from esp8266. Then for all the rest, forget the Arduino.

You need a dedicated MP3 decoder chip (many out there, sta013 was one of the oldest beasts) which can take the digital mp3 stream and convert it to analog output.

You can feed the line level analog output to the FM Transmitter, and then you're golden.

Note that you shall develop some application on the PC to actually stream out the MP3 - an off the shelf solution such as a Shoutcast server may not work, as the usual web-radio stations inject station data and currently played track metadata into the mp3 stream what you have to remove from the MP3 decoder chip.

Since the actual wifi bandwidth with ESP is limited (as well as the processing power of the Arduino), you may switch to a more efficient compression format. For example, a 64kbps WMA sounds far better than a 64kbps MP3, and at 64kbps AAC is superior to any of the other formats. Ensure that your decoder chip can work well with a modern codec comperssion format.


Migrating from ATMega2560 to ARM based -- Teensy vs Due?

If compatability is what you are after I would say go for the Due. If good products are what you are after, go for the Teeensy. The Due, being a real Arduino, will have the best software support and forum community and thus the best chance of getting existing libraries to work with it. The Teensy, because the project really centers around one guy's brilliance, is highly dependant on that one person's time, and while he has done a stirling job with the Teeensy core, he is still only one guy and can only do so much. So it may be harder to get third party libraries working on it.

That said, the Due is not a nice board. The SAM3X chips are awful. Any chip that needs an erase button attached to it to get around the "possibility it won't be able to enter the bootloader" (which incidentally is hard coded in ROM and can NEVER be replaced or upgraded) is destined for the scrap heap IMHO.

There are of course other options as well. There are about a million and one ARM based Arduino-like boards out there with varying amounts of support, either from the chip manufacturer (such as the ST boards), or third party builders. Then of course there are other architectures that are in my biased opinion much better than the ARM ones - chips such as the MIPS based PIC32, used in the chipKIT family of boards. Those latter though don't yet have a port of the SdFat library yet, although it is something that is being actively worked on. There are even Sparc based boards out there that are worth a look.


Does enabling the Timer1 CompareA interrupt instantly triggers an interrupt?

The project behaves as if enabling timer compare interrupts instantly
  triggered one

This can indeed happen, and it's likely what you are experiencing.

Explanation: an interrupt fires when three bits are simultaneously set:

the “interrupt flag” that signals the detection of some specific event
the “interrupt enable” bit associated with that particular interrupt
the “global interrupt enable” bit that is set by the sei()
instruction

In your case, the relevant interrupt flag is OCF1A (Timer/Counter1,
Output Compare A Match Flag), in register TIFR1 (Timer/Counter1
Interrupt Flag Register). This flag is raised by a “timer compare”
event, i.e. when the timer value hits the value stored in OCR1A. If
the interrupt fires, the flag is automatically cleared when the CPU
starts executing the corresponding ISR. Alternatively, the flag can be
cleared manually by overwriting it with a logic 1 (yes, that's kind of
backwards). It is worth noting that the flag records the compare events
whether or not the interrupt is enabled.

You normally expect the interrupt flag to be the last of these three
bits to be set, so that the interrupt is triggered by the compare event.
But this need not be the case. In your program, it is likely that the
interrupt flag is raised one second after startup. The global interrupt
enable is set by your sei() at the end of setup(). Thus, at this
point, as soon as you set the interrupt enable bit the interrupt fires
immediately.

The standard solution to this problem is to clear the interrupt flag
right before setting the interrupt enable bit:

TIFR1  |= _BV(OCF1A);   // clear timer compare flag
TIMSK1 |= _BV(OCIE1A);  // enable timer compare interrupt


From the Arduino Nano at Arduino.CC:

  The Arduino Nano can be powered via the Mini-B USB connection, 6-20V unregulated external power supply (pin 30), or 5V regulated external power supply (pin 27). The power source is automatically selected to the highest voltage source.

Or, take if from the schematic:


Powering Arduino Mega 2560 from a Raspberry Pi Usb

If you are powering your RPi from power supply 5V/2A at least there should be no problem. USB hub on the RPi should not give more than 500mA to power Arduino. Also there is a fuse on Arduino's board to prevent any damage from USB power.

Check both Arduino and RPi schematics for more details about modules used there:

Arduino
Raspberry


Is it correct to use a 9V 1A transformer to power my project?

in all places recommend not to use sources that give currents greater than 500mA when you are going to feed it by the pin VIn with 9V.

Nowhere says that.  They say you should not draw more than 500mA when you supply with 9V.

The heat generated by the 5V voltage regulator is proportional to the current multiplied by the voltage.  The more current you draw the hotter the regulator will get. The higher the input voltage, the more voltage it has to drop, and thus the hotter it gets.

So the higher the input voltage the lower the current drawn by your project can be before the regulator gets too hot.

Since you are only around 300mA that's below the recommended maximum for a 9V input.


Check your battery, it is behaving like a rechargeable one without a charger.  Mine have the letter "R" at the end of the part number.  There are a lot of RTC modules that charge the battery. Conversely they are some that do not charge the battery. Are you powering it with something other then the coin cell.


I figure out a solution - I just needed to use a relay.

I didn't know what a relay was, and had a hard time figuring it out.  I've included some notes for anyone who finds this post in the future.

I can't determine if it took reading 3-4 articles on relays for it to sink in, or if one article was the best.  Anyway, for me this one helped the most: https://www.instructables.com/id/How-Electronic-Switches-Work-For-Noobs-Relays-and/
My relay looked different from most of the tutorials.  I figured it out by connecting a couple alligator clips to a 9v battery and listening for the click of the magnetic switch.  Then I used my volt meter to determine which leads were working with the relay.

Relay Setup:

I connected my ~5 to one lead on the relay, and 5v to the other
The Common (middle) lead connects to one terminal on the garage door opener
The N/C (Normally Closed) lead connects to the other terminal on the garage door opener

Button Setup:

The button setup was just like all the other button tutorials
When the button is pressed (LOW), I start and stop the relay to trigger a "button press" for the garage door opener (it starts)
I then run a delay for the set amount of time I want
All button presses are ignored until after the delay has finished

Now I can move on to the actual project.  Thanks!


Using union to return a range of bits from a data frame: wrong approach?

You are using a union so you have to specify which part of the union you want. Your function should read:

 signed long DJ_ED()
{
  pack5 ED;
  ED.ints[0] = (DJ_buf[3] >> 5) & 1;
  ED.ints[1] = (DJ_buf[3] >> 6) & 1;
  ED.ints[2] = (DJ_buf[3] >> 7) & 1;
  ED.ints[3] = (DJ_buf[2] >> 5) & 1;
  ED.ints[4] = (DJ_buf[2] >> 6) & 1;

  return ED.value;
}

It still looks wrong because you are only putting a single bit into those 5 bytes (because of the & 1). And 5 x int will be a lot longer than one signed long.

The code below seems to match the data structure you posted an image of:

struct packedFields
{
  // byte 0
  unsigned int sx      : 5;
  unsigned int rtt_4_3 : 3;

  // byte 1
  unsigned int sy      : 5;
  unsigned int rtt_2_1 : 3;

  // byte 2
  unsigned int rtt_5   : 1;
  unsigned int cs      : 4;
  unsigned int ed_4_3  : 2;
  unsigned int rtt_0   : 1;

  // byte 3
  unsigned int ltt_4_0  : 5;
  unsigned int ed       : 3;

  // byte 4
  unsigned int ltt_5    : 1;
  unsigned int rbr      : 1;
  unsigned int b_plus   : 1;
  unsigned int filler_2 : 1;
  unsigned int b_minus  : 1;
  unsigned int lbr      : 1;
  unsigned int filler_1 : 2;

  // byte 5
  unsigned int filler_4 : 2;
  unsigned int rbb      : 1;
  unsigned int lbg      : 1;
  unsigned int be       : 1;
  unsigned int rbg      : 1;
  unsigned int filler_3 : 1;
  unsigned int lbb      : 1;

};

union packedFieldsUnion
  {
  packedFields a;
  byte b [6];
  };

void doSomethingWithTheFields (packedFieldsUnion & theFields);  // prototype
void doSomethingWithTheFields (packedFieldsUnion & theFields)
  {
  theFields.a.rtt_4_3 = 3;
  theFields.a.ltt_4_0 = 2;
  }  // end of doSomethingWithTheFields

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("packedFields sized = "));
  Serial.println (sizeof (packedFields));

  packedFieldsUnion foo;
  memset (&foo, 0, sizeof foo);

  doSomethingWithTheFields (foo);

  Serial.println (F("-- packedFields bytes --"));
  for (int i = 0; i < sizeof foo; i++)
    Serial.println ((int) foo.b [i], HEX);

  }  // end of setup

void loop ()
  {
  }  // end of loop

I have a bitwise struct, as Ignacio Vazquez-Abrams suggested. Testing indicates you put the low-order bits first. Then I made a union of this struct and 6 bytes. You can't fit the whole thing into a signed long anyway (a long is 4 bytes) so that part of your code was doomed to fail.

A small bit of test code proves that the bits are being accessed in the correct way. You still need to fiddle around with things like RTT which has individual bits scattered in different places.

If you look at the data format you posted there are 6 bytes, not 5. They are numbered 0, 1, 2, 3, 4, 5. A total of six of them.


Arduino button-controlled LED with AVR Assembly

Fixed it with the below code for the loop:

loop:
  sbic PIND, 2
  call nopressb
  ; button pressed
  ldi r16, 0b00100000
  out PORTB, r16
  rjmp loop
nopressb:
  ldi r16, 0b00000000
  out PORTB, r16
  rjmp loop


Having trouble with sprintf function and string class

Create them as char arrays like this:
const char* menu[2] = {"Menu 1", "Menu 2"};

and use them like this:
Serial.println(menu[0]);


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

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

:01001E0023BE
:00000001FF

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

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

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

See the avrdude manpage for explanation.

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

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

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


Need to "Extend" a Arduino Digital Signal

The scenario you are referring to - connecting one output to many devices - is called the fan-out. Yes, a GPIO pin has a limited amount of drive which limits the number of devices in the fan-out.

There are two problems that are caused by excess fan-out:

Excess current draw from resistive loads
Excess capacitance from logic loads

The former is evident when you have too many LEDs connected directly to an output (with resistors, of course). The combined current draw of the LEDs exceeds the current the IO pin can provide and either damage the pin or the LEDs go dimmer than would be desired.

The latter is more evident when working with communication signals. The excess capacitance imposed by each gate attached to the output causes a low-pass filter effect which can filter out high-frequency signals or corrupt the waveforms by removing higher frequency components and "curving off" the nice clean square waves.

In normal logic systems it's common to use line drivers or buffers to allow the connection of more devices to a single signal. Devices such as the 74HC244, which is 8 buffers in one chip, are commonly employed. You can connect the inputs of all 8 buffers to one Arduino output, and each output from the buffer mirrors the input exactly and can connect to more devices than an Arduino can (each output has an extra 10mA steady-state drive capacity than the Arduino).

And yes, you can even connect the output of one buffer to the inputs of other buffers to give even more capacity.

simulate this circuit – Schematic created using CircuitLab


Button and switch to turn on and off LED and changing after time

I have to make an answer, since I cannot use items/links easily in a comment.

Instead of creating the application for you, I suggest you do the following:

Read/try and experiment with the default Arduino examples for a switch (see Switch
In the above example also is shown how to debounce the signal, this is needed since you want to use it as a 'toggle'.
Use a timer for millis() and check for 24 hrs (which is 1,440,000) millis, so it should fit in a long.
Small thing: Always align brackets to make it easier for yourself and others.