The only way I can think of accomplishing this without some sort of proximity sensor is to measure the signal strength of the XBees.

From page 41 of the datasheet:

  DB (Received Signal Strength) Command

  AT Command: ATDB

  Parameter Range [read-only]:  0x17-0x5C (XBee), 0x24-0x64 (XBee-PRO)

   DB parameter is used to read the received signal
  strength (in dBm) of the last RF packet received. Reported values are
  accurate between -40 dBm and the RF module's receiver sensitivity.
  Absolute values are reported. For example: 0x58 = -88 dBm (decimal).
  If no packets have been received (since last reset, power cycle or
  sleep event), “0” will be reported.

You can use this as a rough estimate of the distance between two sensors. You will have to correlate signal strength to actual distance and obstructions and other factors will cause the reported value to be off.

How to measure XBee signal strength?

This page has an example using Processing (on the computer): XBee Signal Strength


How does the Arduino handle serial buffer overflow?

For hardware serial ports you can see in HardwareSerial.cpp that the buffer size varies depending on the amount of RAM available on the particular AVR:

#if (RAMEND < 1000)
    #define SERIAL_BUFFER_SIZE 16
#else
    #define SERIAL_BUFFER_SIZE 64
#endif

For a software serial port in SoftwareSerial.h the receiver buffer size _SS_MAX_RX_BUFF is defined as 64 bytes. In both cases it stops attempting to insert received data into the queue when it is full, so you could get a mix to old and new data depending on how you're retrieving data from the queue.

Ideally it would be best to ensure the buffer always gets emptied in a prompt manner to avoid the buffer filling. Maybe take a look at timers and implementing a simple state machine if your problem is related to other code blocking the main loop.


I was wondering if it's possible to get signal strength from the module

No, it doesn't appear so from the data sheet / AT command list.

  Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

Yes, and it can get the signal strengths.  You should be able to get an HC-05 module on a breakout board from Ebay for less than $10 delivered.  There's also a method to update the HC-06 firmware to be an HC-05 but it's probably easier for you to buy one.


Control DC Motor with Arduino Uno WiFi Rev2 Html Slider Code

Here's an example of slider that changes a Servo speed,
In html page code you have to add this:

  <input type="range" min="0" max="1023" value="512" class="slider" id="myRange">

Value:

In arduino you have to define handler like this:

void handle_pwm() {
 String  pwm_val = server.arg("PWMval"); // reading from slider on html pagae

 Serial.print("slider val: ");
 Serial.println(pwm_val);
int pwm_value = map(pwm_val.toInt(), 0, 1023, 0, 180);
Servo.write(pwm_value);

server.send(200,"text/plane","0"); // handling the webpage update

}

And define servo and handler in Setup() section:

void setup(void){
....
Servo.attach(MotorPin,1000,2000);
server.on("/setPWM", handle_pwm);
....
 }


ESP32 send data to another ESP32 without establishing a wifi connection

Finally I found a way how to do it. If you use the mac address FF:FF:FF:FF:FF:FF that works as a broadcast address. This is the working code on how to send a message from the master to another esp32 without knowing its mac address. Later the slave can reply with its real mac address:
Code for master (tx)
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success 1" : "Delivery Fail 1");
  if (status ==0){
    Serial.println("Delivery Success 2");
  }
  else{
    Serial.println("Delivery fail 2");
  }

  Serial.println();
}

void setup()
{

  Serial.begin(115200);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Once ESPNow is successfully Init, we will register for Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);

   // Register peer
  esp_now_peer_info_t peerInfo;
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

   // Add peer
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }
}

int dataToSend = 1;
void loop()
{
    dataToSend++;

    // Send message via ESP-NOW (size of an int is 4 bytes on ESP32)
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &dataToSend, 4);

    if (result == ESP_OK) {
      Serial.println("Sent with success");
    }
    else {
      Serial.println("Error sending the data");
    }

    //Serial.println(WiFi.macAddress());
    delay(1000);
}

Code for slave (Rx)
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len)
{
  int dataReceived;
  memcpy(&dataReceived, incomingData, sizeof(dataReceived));

  Serial.print("Data Received: ");
  Serial.println(dataReceived);

  Serial.println();
}

void setup()
{

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

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  // print our mac address
  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);

}

void loop()
{
}

You can also reply back on the receiver code if you want. It will be the same code.


Pin 0(RX) and 1(TX) and the RESET pins are important to upload a sketch. Can you check those carefully with a magnifier ? Perhaps there is some solder that shortcuts to something else, or perhaps you damaged a copper trace.


How to find the deferenced value of a transmit Port Register?

My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

No.  You're mistaking the operator.  In this context & means the address of, so it is getting the address of the variable called PORTD and casting it to an unsigned 16-bit integer, which it's then storing in the array.

  Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

Again, we're talking addresses.  The port register number is (for port D) 0x0B.  Add that to 0x20 and you get 0x2B which is the address of the register in memory.  Then comes the tricky bit:

#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Expand that out with 0x2B and you get:

(*(volatile uint8_t *)(0x2B))

Now, working from the inside out we have:

(volatile uint8_t *)(0x2B)

That says this is a pointer to address 0x2B.

Then that is de-referenced to get the value from that pointer with a * operator:

*(volatile uint8_t *)(0x2B)

So you end up with "The value that is in the address 0x2B"

If we then feed that back into the first part of your question, so:

PORTD = (*(volatile uint8_t *)(0x2B))

then &PORTD would be:

&(*(volatile uint8_t *)(0x2B))

The initial & and * cancel each other out (you can think of them as opposites - one is get the address from a value, the other get a value from an address), so you effectively end up with:

(volatile uint8_t *)0x2B


Arduino Uno R1 I soldered resistor but I cannot DFU program atmega8u2

According to https://gebloggendings.wordpress.com/category/elektronik/arduino/ it is sometimes not to assume that the atmega8u2 is always the correct value in my case was the at90usb82 resulting into using the following command sequence:

sudo dfu-programmer at90usb82 erase
# Flashing the arduino provided .hex
sudo dfu-programmer at90usb82 /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/Arduino-usbserial-uno.hex
# reset the board
sudo dfu-programmer at90usb82 reset

Further information you can find into:

https://forum.arduino.cc/index.php?topic=53443.0
https://forum.arduino.cc/index.php?topic=542854.0


If the problem is due to jittery pot readings, you may want to smooth the potval data sequence by code like the following, where rawreading stands for what you just read from the potentiometer's input line.

potval = alpha*potval + (1-alpha)*rawreading;

Set alpha to a number (eg 0.8 or 0.9 or 0.95 etc) between 0 and 1.  alpha represents the fraction of the old value that you retain, and  1-alpha represents the fractional influence of the new raw reading.   alpha closer to 1 causes smoother but slower response.

If you prefer integer arithmetic for faster or smaller code, then represent alpha as a ratio of integers.  For example:

potval = (potval*12 + rawreading)/13;

The technique mentioned above is called exponential smoothing or  exponential moving average.


Send and receive text between Arduino Mega 2560 and C# via ENC28J60

You can use TCP or UDP protocols.

https://www.arduino.cc/en/Tutorial/UDPSendReceiveString

https://www.arduino.cc/en/Tutorial/DhcpChatServer

You can use free UDP, TCP port listener sofwares for Windows, Linux etc.. for testing your setup.

For C# development:

https://stackoverflow.com/questions/20038943/simple-udp-example-to-send-and-receive-data-from-same-socket

and

https://stackoverflow.com/questions/10182751/server-client-send-receive-simple-text


How many I2C lines does the Arduino Due have?

According to the Wire library documentation https://forum.arduino.cc/index.php?topic=132130.0:

  The Arduino Due has two I2C / TWI interfaces SDA1 and SCL1 are near to
  the AREF pin and the additional one is on pins 20 and 21.

And the table:

Arduino Due: 20 (SDA), 21 (SCL), SDA1, SCL1

So it seems in your table SCL2 should be SCL1.


As you have noted, many Arduino (and clones) are rated for supply voltage up to 12V. But note that if you use 12V power, the on-board regulator will get rather hot.  Providing decent ventilation and maybe even extra heat sink would be a good idea.


SoftwareSerial receives beginning of data mangled

I like the readBytes or readBytesUntil function. It doesn't end on a small gap between received bytes and fills the buffer. This functions are blocking with timeout, but if read some other device the input is usually fast and terminated reliably.

example for readBytesUntil:

if (Serial.available()) {
  char buff[32];
  int l = Serial.readBytesUntil('\n', buff, sizeof(buff));
  if (l > 0 && buff[l - 1] == '\r') {
    l--; // to remove \r if it is there
  }
  buff[l] = 0; // terminate the string
  Serial.println(buff);
}


Arduino: Reading DS18B20 interferes with servo

Arduino's Servo library on AVR uses interrupts; if interrupts are disabled for any amount of time, the servos will twitch.

1-Wire protocol (used by DS18B20) needs to disable interrupts for the protocol to work. Therefore, servos glitch.

There is a great explanation of the problem here: https://learn.adafruit.com/neopixels-and-servos/overview , just mentally replace "Neopixel library" with "OneWire library". Their TiCo_Servo library sounds just like what you want.


I contacted MaxBotix with the problem and for my surprise their technical support is really great:

  The Arduino is set up to natively read TTL serial data.The MB7066 outputs its serial data in the RS232 format. Do not worry; this problem can easily be fixed. You can use an inverter such as the MAX232. You can also follow the following tutorial to make your own https://github.com/simonmonk/raspirobotboard/wiki/Rangefinder-Adapter.

  Another option would be to test using this code section SoftwareSerial
  sonarSerial(rxPin, txPin, true); //define serial port for recieving
  data, output from maxSonar is inverted requiring true to be set.


how to run 2 different servo (continuous rotation and regular servo) in parallel, not run one after other?

I am proposing one answer
https://wokwi.com/arduino/projects/297646292038844936
Here, we are not using the delay function. We are using the millis()
Based on your actual application, you can control individual servo accordingly.
Here is the Arduino simulation:
https://wokwi.com/arduino/projects/297646292038844936

/* Sweep
  by BARRAGAN <http://barraganstudio.com>
  This example code is in the public domain.

  modified 8 Nov 2013
  by Scott Fitzgerald
  http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
Servo myservo2;  // create servo object to control a servo

// twelve servo objects can be created on most boards
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 15;           // interval at which to blink (milliseconds)

int pos = 0;    // variable to store the servo position
int pos2 = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo2.attach(10);  // attaches the servo on pin 9 to the servo object

}

void loop() {
  unsigned long currentMillis = millis();

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

    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    pos = pos + 1;
    if (pos > 180) {
      pos = 0;
    }                      // waits 15ms for the servo to reach the position

    myservo2.write(pos2);              // tell servo to go to position in variable 'pos'
    pos2 = pos2 + 1;
    if (pos2 > 90) {
      pos2 = 0;
    }

  }

}


Arduino Yun C++ environment? Bridge + Cross-Compiler

The Linux side of the Yun is just an OpenWRT installation. It has hardly been modified at all.

To cross-compile you will first need a Linux computer, or a Linux virtual machine.  Then you need to download the OpenWRT source code and configure it for the Yun (I think it defaults to the right settings).  Then you can build the whole OpenWRT image.  One side-effect of that is it compiles and configures a full cross-compiling environment for you.

You can then use that cross-compiling environment to compile your own code.


Arduino: Hardware SPI hangs, bit-bang does not

According to ATmega32u4 datasheet, section 17.2.1 (SPI / SS Pin Functionality / Master Mode:

  If SS is configured as an input, it must be held high to ensure Master SPI operation.

In your circuit, SS pin (#8 on package), also labeled as "(SS/PCINT0) PB0", is left unconnected.

Is it possible that PB0 is also configured as input somewhere in your program or libraries? In this case, it should be connected to Vcc.


Error while inputting EEPROM.read() and EEPROM.write()

Have you looked at any Arduino IDE example programs?
They all have a setup() and loop() function.
Apparently, Tinkercad is missing the loop() function in your code.
You can solve the issue by adding an empty void loop() { } after your void setup() { ... } code.


Is there something like a Virtual Environment for Arduino?

Sorry, but in Arduino IDE no such functionality as virtual enviroment. To add your own version of libraries to each projects you may only add it (libraries) directly to a project dir.


Using Arduino project migrated to breadboard with 12 MHz crystal instead of 16 MHz

Some of the code running on the microcontroller needs to know the clock speed it's running at for correct timing. For this reason the macro F_CPU is set with this value. In the Arduino IDE this value is commonly defined in the boards.txt build.f_cpu property. If you're using a bootloader(which is used for uploading sketches over serial) it also needs to know the clock speed so that it can get the baud rate of the upload correct. The bootloader is not compiled in the Arduino IDE so it is not affected by your setting in boards.txt. You can recompile the bootloader with the correct clock speed setting and then install the compiled file on your microcontroller using an ISP.

There is a much more simple solution. All the hard work has already been done for you in MiniCore:
https://github.com/MCUdude/MiniCore

You only need to:

Install MiniCore following the instructions at https://github.com/MCUdude/MiniCore
Tools > Board > ATmega328
Tools > Variant > 328P / 328PA
Tools > Clock > 12 MHz external
Tools > Burn Bootloader


Trinket works with USB but not with wall adapter

Yes, you are probably over-powering the trinket. The trinket expects 5V on the USB connector. However, it has an voltage regulator on board that can take up to 16V.

The BAT pin is connected to the voltage regulator and can take anywhere from 5.5V to 16V.


There is probably somewhere else, like this:

#define LOW 0

Which means the pre-processor turns your line from this:

volatile byte state = LOW;

into this:

volatile byte state = 0;

There is nothing arduino-specific here, just the use of standard C/C++ features.


Best buffering practice for continuous SD card writing

Is this a sensible solution to the problem?

No, unfortunately not. The size of the buffer is limited by the available RAM on your chip. Jumping between multiple buffers or cores will not change that, since it is a hardware limitation.

I am hesitant to implement anything that simply relies on an improvement in SD write speed, as I will likely need to increase the size of the data payload in the future and don't want to run into this issue again later on.

When you are continuously receiving faster than you can write, you only have 2 options:

Improve write speed
Reduce the needed data size

There is no other way, and that's a logical conclusion, not so much a programmical or hardware conclusion. It that situation the amount of "buffered" data will increase indefinitely, so you would need an infinite amount of memory. And that doesn't exist in real world. The same principle would apply to a high end PC with lots of memory, it will just be full after longer time, than with an ESP.

Improving write speed:

On various sites I have read, that you can use the SD card with different SPI frequencies. A higher frequency would mean a higher transaction speed. You can investigate further at this point.
Writing a full 512 byte page at once and only closing and opening the file again, if really needed, will improve the overall speed.

Reduce the needed data size

Maybe you can compromise with your data resolution and then pack those values as dense as possible (like packing two 4-bit values into a single byte of transmission).
You can research for compression code, so that you can compress your data lossless before transmitting it. Though the result will always depend on the kind of your data. Also mind, that in this case you are trading transmission size for computation time and RAM.

About buffers:
I would say, a normal circular buffer does not bring you much advantages here, since with the SD card you don't want to do bytewise data transmission. The 2 buffer approach, that you mentioned, seems good to me. Though doing handling with different cores does not make much sense to me. The UART receiving itself is done by hardware and some ISRs. You can do all the SD card transmissions in your main code, just making sure, that you regularly copy the received data from the Serial buffer into your buffer.


Arduino clone woks only with USB - NOT with external power

It sounds like there's some form of short, or the AM1117 regulator is dead. Too much current being drawn by the regulator (as it gets so hot) has caused the diode to blow.

You will need to replace both the regulator and the diode and hope it works - or use a separate external regulator into the 5V pin instead.

Personally, I'd use a switch-mode regulator (UBEC regulators are cheap and easy to get hold of) since it is far more efficient than the LM1117.


About two weeks ago there was a change in the Arduino_SensorKit Library that introduced an error with the instanciation of the Oled object.
I found the error in the release (v1.0.6) of the library. The previous release (v1.0.5) could cause another issue, as it uses a software I2C. I doubt the hardwired sensores are connected with the correct pins. But I have no hardware, so I can not check this.
I propose a workaround to see, if the identified issue caused your observations.
#include "Arduino_SensorKit.h"

U8X8_SSD1306_128X64_NONAME_HW_I2C Oled2;
// if the line above does not work
// comment it and uncomment the following line.
// U8X8_SSD1306_128X64_NONAME_HW_I2C Oled2(U8X8_PIN_NONE);

void setup()
{
  Oled2.begin();
  Oled2.setFlipMode(true);
  Oled2.setFont(u8x8_font_7x14B_1x2_r);

  Pressure.begin();
}

void loop()
{
  Oled2.clear();

  Oled2.setCursor(0, 10);
  Oled2.print("Temp: ");
  Oled2.print(Pressure.readTemperature());
  Oled2.print(" C");

  delay(1000);
}

Could you please try out and report your experience.
If it would work, I can support the fixing of the issue.


@MikaelPatel answered your question in the comments:

  That gives a total of 54K pixels. And with 4-bit per pixel, two pixels
  in a byte, 27K byte to store a packed off-screen bitmap. Even an
  Arduino Mega would have too little memory for that. This might explain
  why there are no supporting library for that device.


Wirelessly communicate between two Arduinos without router

I can highly recommend these cheap little 433Mhz radios.  You can get them on amazon, ebay, etc. and they work pretty well for me. Your distances are a bit longer than my situation but I have to go through several walls.


The code that's sent to Arduino is "compiled" which means it's changed from human readable form to a binary data that can be understood by the processor. The "code" you wrote remains on your computer only.

This itself is a way of encryption since it's impossible to retrieve the original source code from that binary data. That data can only be "decompiled". This is a process that takes the binary data and converts it automatically into a human readable code, but it's not the same code that you originally made. It doesn't have comments, and logical variable names. This makes it also hard to understand.

Decompilation is usually to difficult and time consuming to even bother doing that unless your hardware is a lock on a vault with million dollars inside. If that's the case don't use Arduino, but instead use a custom designed chip with cryptographic key built inside the hardware.


Particle Spark (Arduino) How to flash 2 LED sequences at the same time?

I cover this exact question in my web page: http://www.gammon.com.au/blink

Example code that blinks two LEDs at different rates:

// Which pins are connected to which LED
const byte greenLED = 12;
const byte redLED = 13;

// Time periods of blinks in milliseconds (1000 to a second).
const unsigned long greenLEDinterval = 500;
const unsigned long redLEDinterval = 1000;

// Variable holding the timer value so far. One for each "Timer"
unsigned long greenLEDtimer;
unsigned long redLEDtimer;

void setup ()
  {
  pinMode (greenLED, OUTPUT);
  pinMode (redLED, OUTPUT);
  greenLEDtimer = millis ();
  redLEDtimer = millis ();
  }  // end of setup

void toggleGreenLED ()
  {
   if (digitalRead (greenLED) == LOW)
      digitalWrite (greenLED, HIGH);
   else
      digitalWrite (greenLED, LOW);

  // remember when we toggled it
  greenLEDtimer = millis ();
  }  // end of toggleGreenLED

void toggleRedLED ()
  {
   if (digitalRead (redLED) == LOW)
      digitalWrite (redLED, HIGH);
   else
      digitalWrite (redLED, LOW);

  // remember when we toggled it
  redLEDtimer = millis ();
  }  // end of toggleRedLED

void loop ()
  {

  // Handling the blink of one LED.
  if ( (millis () - greenLEDtimer) >= greenLEDinterval)
     toggleGreenLED ();

  // The other LED is controlled the same way. Repeat for more LEDs
  if ( (millis () - redLEDtimer) >= redLEDinterval)
    toggleRedLED ();

/* Other code that needs to execute goes here.
   It will be called many thousand times per second because the above code
   does not wait for the LED blink interval to finish. */

}  // end of loop


Use an Arduino to "intercept" transparently serial communication to Grbl?

I finally solved my problem by buying an Arduino Due! It was a problem of speed, not of code. The Uno is just not powerfull enough to read an write to Software Serial at 115200 Bauds, or even 9600, which I tried.

The Due has absolutly no problem. I made a small code test to intercept "words" coming form "USB" To "GRBL", and it works just as expected, while GCODE is send (using Grbl-Panel on the PC) through the Due (USB) to the Uno (Grbl).

It's the very first time I solve what I thought to be a code problem by an hardware solution.

BTW, in case anyone wonder, yes, I am using a level shifter between the 2.


You are measuring a sinusoidal "signal" that is alternating in polarity. What the code notes as "effective" current the equivalent DC current for purposes of measuring power consumption. In EE, it's called "RMS" or Root Mean Square, and it's the mathematical derivation to calculate consumed power or current in a situation where the current flows symmetrically back and forth, and thus a time average would give zero.

It's dividing the peak current by the square-root of 2 (1.414).


You can't. Variables and macros are completely different concepts and handled by completely different parts of the compiler toolchain.
Instead you will need to build your string up into a char array (or whatever format the _user_gcode_exec() function accepts) with the likes of sprintf.


Arduino connecting relay has no power output

It sounds, from your textual description (please post a schematic or at least a photo of your setup) that you aren't providing power to the relay.

A relay doesn't have a power output.  It never provides power - it is merely a magnetically operated switch.  It is used to switch an external source of power on and off.

Treat the NO and COM pins as either side of a normal button or switch and wire it accordingly - that is (for example) connect COM to the positive of your power supply, NO to one side of your load, and the other side of your load to the negative of your power supply.

You can share the same power supply as you are feeding to the logic / drive side of the relays.


Is it possible to run two small motors off an Arduino and have the motors move separately based on a random number generator?

Leaving your mechanical equipment uncommented *), an Arduino itself cannot drive 7.4V 1A Stepper Motors. An Arduino itself cannot drive any motor. You need a sufficient power supply and motor driver electronics. And there's a vast amount of different devices to choose from.

But then, the answer to "is it possible (random, two motors, moving independently)" is yes.

*) Well, regarding "uncommented" :
200 lbs is quite heavy to simulate/produce a few raindrops. Small motors won't move such gear as in your pic.


Is it possible to transmit radio signal with cheap 433Mhz transmitter as strings and receive it with an RTL-SDR

In general you can use RTL-SDR to decode any AM and FM modulated signals (+some digital modulations) that lie within the frequency range form roughly 50MHz to about 1GHz. So 433MHz is confortably within that range.

There are many projects on GitHub that leverage the RTL-SDRs ability to decote 433MHz OOK modulated signals like:

RTL_433
Which comes with a ton of decoders for various appliances.

OOK_Decoder
Which will give you the demodulated raw output for you to decode the bits yourself.

I'm sure you will find more but those are in my opinion the most noteworthy for the 433MHz OOK space.


Arduino Wire.h library: how to communicate with an LCD?

SOLVED!

I forgot to write beginTransmission(). Here's my code:

#include <Wire.h>

void setup() {
  Wire.begin(0x63);
}

void loop() {
  Wire.beginTransmission(0x63);
  Wire.write(byte(0x00));
  Wire.write("Temperatur:");
  Wire.endTransmission();
}


Right now I have it on Arduino Nano/Atmega328 + AVRISP mkII

Tha AVRISP is not an FTDI programmer. How do you have it wired up?

See: How to make an Arduino-compatible minimal board

From that page, this is how I hooked up my FTDI cable:

And a close-up:

You need RTS, via a 0.1 µF capacitor (in series) in order to trigger a reset.


Sending data from txt file over serial connection

I don't know the details of why the hang is occurring.  However, the problem stems from serial ports being available to one process at a time.  When the Arduino-environment's serial-port-monitor opens a serial port, that port becomes unavailable to bash.  (To close the hung Arduino IDE process and the SPM, say ps aux |grep arduino and kill n, where n is the PID shown by the ps and grep.)

Here is a python program you can run, that sends and receives data:

#!/usr/bin/env python
# Send data to an Arduino and report responses.
from time import time, sleep, asctime, localtime
from serial import Serial
print 'Opening serial port'
ser = Serial('/dev/ttyACM0', 9600, timeout=3)
sleep(1)                      # Let board initialize
while 1:
    txt = 'It is about ' + asctime(localtime()) + ' now'
    print 'Sending  "{}"'.format(txt)
    ser.write(txt)
    s = ser.readline()          # Get result from arduino
    print 'Readback "{}" at {}'.format(s, asctime(localtime()))
    sleep(1)

Here is some sample output from it, with your sketch runing in a Mega2650.  (I'm not sure why the readback is taking so long as it apparently is.)

Opening serial port
Sending  "It is about Fri May  8 16:48:41 2015 now"
Readback "It is about Fri May  8 16:48:41 2015 now" at Fri May  8 16:48:44 2015
Sending  "It is about Fri May  8 16:48:45 2015 now"
Readback "It is about Fri May  8 16:48:45 2015 now" at Fri May  8 16:48:48 2015
Sending  "It is about Fri May  8 16:48:49 2015 now"
Readback "It is about Fri May  8 16:48:49 2015 now" at Fri May  8 16:48:52 2015
Sending  "It is about Fri May  8 16:48:53 2015 now"
Readback "It is about Fri May  8 16:48:53 2015 now" at Fri May  8 16:48:56 2015


Which external programmers work reliably with Arduino Mega?

I have successfully used Arduino as ISP (not to be confused with Arduino ISP) on a Mega clone that has a funky FTDI-clone onboard, and would not let me upload bootloader through serial. This worked fine, and is cheap.


The reasons it's not updating is because your code is sitting in the loop while (finished == false) {...} waiting for more json to arrive.

Try replacing the while loop with something along these lines:

  while ((finished == false) || Serial.available()) {
   if (Serial.available()) {
    const char in = Serial.read();
    if (in == '{')  {
        response = "";  // Blank the string
        begin = true;
        finished = false;
    }
    if (begin)
        response += (in); // Only write if within the {}
    if (in == '}') {
        begin = false;   // Prevent any chars between } and { leaking through.
        finished = true;
    }
   }
  }

and change the initial variable declarations at the start of the code to set finished to false:

// personally I always put each variables on a separate lines when setting initial values.
bool begin = false;
bool finished = false;

This will block until it's received at least 1 json string. After that it will check if there is new data on the serial port, if there is it will block until it's received the whole string, it there isn't any data waiting it will exit.

Oh and your response string is currently including the { } characters at the start and end, this contradicts your comments which imply that it doesn't.


Addressing EACH of the 3x3x3 LEDs separately

No, the three transistors are there to select the layer you want to control. At every moment only ONE layer can be on. But if you switch through controlling these layers fast enough, you can create the illusion of having multiple leds on even across layers. THis is because the human eyes are just not capable of seeing lights flashing at a high rate.

TL;DR
No you can't address them individually, but you can create the illusion that you can.


Can't Turn Off Internal I2C Pull-Ups on ESP32

I have solved this problem. For anyone who would like to turn off the internal pullups on the I2C bus of the ESP32, you need to disable the entire driver before putting the device to sleep.
First, include the peripheral driver library from the IDF:
#include "driver/periph_ctrl.h"

Next, call the following before sleep:
rtc_gpio_isolate(gpio_num_t(SDA));
rtc_gpio_isolate(gpio_num_t(SCL));
periph_module_disable(PERIPH_I2C0_MODULE);
digitalWrite(SDA, 0);
digitalWrite(SCL, 0);

This will stop the ESP32 from pulling up pins 21 and 22 while in deep sleep. Calling display.begin() or wire.begin() will restartthe driver upon wake.


Just a comment about your diagram. The two transistors should not share an Arduino pin in that way. If the pin is pulled high the transistors saturate and your current 'shoots through' from supply straight to ground. Instead assign one Arduino pin to each transistor (using the base resistor in your diagram).


How do I create a 9 bit number based on values from 9 digital inputs?

In your code you would use a 16 bit unsigned integer as your variable. As there is no such thing as a 9 bit type.

If the pins correspond to different ports on your micro, you basically do this:

Read the pin value from the port register, and bit shift to the right bit position then OR with the variable.

Say you had 8 of the LEDS on PORTB (pin 0 - 7 )and the 9th on PORTC (pin 2)

unsigned int ir_inputs = 0

ir_inputs = PORTB; //just reads the register directly
ir_inputs = ir_inputs|((PORTC & 0x04)<<6); //reads the bit on pin 2 then shifts it 6 places to bit 8 (or the 9th bit remember bits always start at 0) and does not affect the other bits

something like that

actually you could put it into a function

unsigned int getIRinputs(void){
    return (unsigned int)PORTB|((PORTC & 0x04)<<6);
}

Easy done

Even if you had the inputs on 9 separate ports the principle is the same.
Read, Shift, OR


First, figure out which port and pin you're using. Then, manipulate them.

DDRC &= ~_BV(PC5);
PORTC |= _BV(PC5);

...

DDRF &= ~_BV(PF5);
PORTF |= _BV(PF5);

...

DDRF &= ~_BV(PF0);
PORTF |= _BV(PF0);


Looks fine to me, I don't see any issues, assuming the PSU has sufficient 'grunt' to power both, and most will have.


Concatenate two non constant char arrays in Arduino

Assuming the data in buffa is a c-style string (i.e. null-terminated), replace

sprintf(buff, "%s", buffa);

with

strcat( buff, buffa );


How to deep sleep ATtiny/ATmega (to run for years with batteries) but still detect a button press?

ATTINY's are designed to easily do this since they can wake from power down sleep mode by a pin change...

Basically you want to...

Connect a normally-open push button between an IO pin and ground.
Enable the pull-up on the IO.
Enable the pin change interrupt on the IO pin.
Enable interrupts.
Enter "power down" sleep mode.

When the button is pushed, it will connect the IO pin to ground, which will cause a pin change interrupt, which will wake the chip from sleep.

Note that you do not need to do anything in the pin change ISR (you can use the EMPTY_INTERRUPT compiler macro). If the ISR is empty, execution will pick up on the line after the sleep upon waking.

While in deep sleep, the chip will use an astonishingly small amount of power.  For example, an ATTINY25/45/85 running off of a 3V coin cell at room temp will use less than 0.2uA...

A typical CR2032 coin cell is rated for 235mAh to 2V, so at this rate we'd expect to be able to wait for a button press like this for 100+ years.

IRL the battery will likely self discharge and physically deteriorate long before then (rated at 1% per year), but still not too shabby.


You don't say what you're using to program it (an FTDI board? the USB adapter on an Arduino?) but you probably want to connect

TX - RX
RX - TX


Change Options for the AVR Programmer via Arduino IDE

Short answer: I'm afraid you can't do it with Arduino IDE 1.0.5.

Long answer:

First of all, be aware that -B20 does not specify the baud rate but the bitclock period (in us); this is specific to stk500v2 programmer.

Normally, enabling your programmer should only be a matter of adding it to the list of programmers known by Arduino IDE; that list can be found in hardware/arduino/programmers.txt. You would then append the following lines at the end of this file:

strangeprogrammer.name=Somehow Strange Programmer
strangeprogrammer.communication=serial
strangeprogrammer.protocol=stk500v2
strangeprogrammer.force=true
strangeprogrammer.speed=?????

However, the problem here is that Arduino IDE does not seem to be able to use flag -B (bitclock period) but only flag -b (baud rate) which value is set to whatever you will put to strangeprogrammer.speed.

At least that's what I could find out by inspecting Arduino IDE source code: AvrdudeUploader.java never adds that flag to the avrdude command-line :-(

That means your options are:

Rebuild the Arduino IDE 1.0 on your own after modifying AvrdudeUploader.java to support -B flag; code should be quite easy (about 2 more lines of Java code).
Switch to Arduino IDE 1.5 and follow Federico's answer :-)
Use another IDE, something that deserves the IDE name. I use Eclipse with this Arduino plugin and it works fine for me. As a bonus, avrdude support seems better as you can see on the screenshot below:


iterate through values in an array of strings to print

I think this is the correct way to create an array of C strings:

    char * hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    char * displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }

Since strings are basically stored as char pointers so an array of strings is an array of char * variables. Or you could create an array of Arduino strings:

    String hvacSystems[] = {"Off", "Fan", "Cool", "Heat"};
    int activeSystem = 0;
    String displayActiveSystem = hvacSystems[activeSystem];

    if(systemNeedsToBeCycled){
        activeSystem++;    // make sure to set a bound for this variable
        displayActiveSystem = hvacSystems[activeSystem];
        tft.print(displayActiveSystem);
    }


Can i use a sparkfun rfid qwiic without an id-xxla?

No. It is not an RFID reader. It just interfaces to an RFID reader. You need an RFID reader to read RFID tags. That Sparkfun board just controls the reader and reads the data from it.


Arduino and SIM900 unavailable all the time

Rather than creating your own function used SerialEvent function in arduino. It acts as a serial interrupt in arduino. For example:

String inputString;
void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          Serial.Println(inputString);
        }
      }
    }


How to embed a 5V-range Arduino-based controller in a 12V-range DC circuit?

Just use a transistor that can handle 12V with the base connected to the Arduino and that's it...

Maybe I didn't get what you were trying to say, but anyway, I think that's what you are looking for.


Not only is it uncalibrateable, but it's actually pretty rubbish (as you've discovered). If you check the datasheet you'll see that it can vary between about 109kHz and 119kHz, even though its nominal frequency is 128kHz.

With the ATmegaXX8(A/P) you can reconfigure the system to run its CPU off the internal RC oscillator and timer 2 from a crystal across TOSC1/TOSC2 (pins 9/10 [DIP] or 7/8 [TQFP]) by setting ASSR[6:5] to 0b01 and changing the CKSEL[3:0] fuse bits to 0b0010. Take careful note of the warning on AS2 in the datasheet though. If you want to use a watch crystal instead of prescaling the existing crystal on an Arduino board then you'll need some soldering skill as well.

If you need crystal accuracy for the CPU as well then you'll need to move up to an AVR family that has a separate asynchronous timer that can be supplied with a watch crystal, such as the ATmegaXX4(P) (Sanguino) or ATmegaXXX0 (Mega/Mega 2560).


one possibility is to use HOST SHIELD
http://www.circuitsathome.com/products-page/arduino-shields

Arduino is now as host
Makey is keyboard


EEPROM: managing address mapping between firmware versions

There's lots of ways you could handle this.

Two thoughts right off the top of my head:

Have a "Version" identifier in the EEPROM.

The firmware then needs to know the EEPROM layout of all versions up to the current one. It can then read the EEPROM from the old version and write back a new format for the current version.

Have each entry in the EEPROM tagged with a "meaning".

This is not too different to your JSON idea (which you are right is horrible), but instead of lots of words you just use a simple number to identify the meaning of the value it is associated with.  Assuming that each stored value is an 8-bit byte (though it doesn't have to be), you could allocate "1" as "set_temperature", "2" as "temperature_hysteresis", "3" as "pid_gains", etc, Then the EEPROM might contain the bytes 1,96,2,5 and the firmware would know that the second byte is the set_temperature because it has a 1 in the first byte.

You can think of it as a "key / value" pair, but both the key and the value are just numbers.

To find the temperature_hysteresis you just scan through all the even EEPROM entries until you find 2, then read the next entry. If you don't find a 2 then you use the default value.

Your firmware can then choose to either update an existing cell that is tagged with the right type (scan for type, update next cell), or it could erase all the values and replace them with just the ones it cares about - the choice is yours.

Any values that your firmware no longer cares about will be ignored, and potentially erased.


The problem with your code is that you are mixing the "normal" and "variadic" forms of the printf functions.

Any printf function starting with V takes a variadic argument list pointer as its last variable. Any printf function which doesn't start with V takes a variadic list of individual variables.

When calculating your buffer size from a list of variables in your main loop you are incorrectly using vsnprintf - you should be using snprintf since you aren't passing it a va_list, but individual variables. In your _printf function you are correctly using vsnprintf to calculate the length of the buffer, but then incorrectly using sprintf with a va_list instead of individual variables.

So your two forms should actually be re-written as:

// Inline version
char buf0[snprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
sprintf(buf0, "pin %i configured to output", PIN);
Serial.println(buf0);

and:

void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  vsprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

Remember: if you have a va_list then it goes with a v*printf function. If you have individual variables they go with a *printf function.


Usually a robot uses 2 identical motors for drive in order to change directions or go straight.  Usually a printer will only have 1 motor to drive the paper and 1 motor to drive the print head.  And usually they are not identical.  Making it difficult to build a useful robot.  Also, printers usually use stepping motors.  Most people building their first (small) robot usually use continuous servo motors.  This makes for an easy to build first (small) robot as seen in this picture:


Reading and Writing on different clock edges with Arduino SPI interface

To set the spi to shift out on falling edge and shifting in on rising edge of the clock you need to set the spi mode to 0 or 2 (depends on idle clock polarity).

More info here

To continuously generate clock signal as far as I remember you will need to write to the SPI dummy values.


availableForWrite() function return error when compiling for Arduino nano 33 BLE

The new Arduino cores use a common API maintained in a separate repository. This was copied from AVR core long time ago and doesn't contain some function added later to other cores. The function Stream.availableForWrite was added to Arduino API repository 5 months ago.

For the Arduino Mbed core they created a branch in the Arduino API repository to move the Arduino core in C++ namespace 'arduino'. But this was before availableForWrite was added. So the API version used in Mbed core doesn't have the function.

I reported it as issue. Even if they add the function to API I doubt they add an implementation of it to Serial.


WARNING: Category '' in library *any library* is not valid. Setting to 'Uncategorized'

Edit or add library.properties to that folder so that you specify a valid category.

Example of library.properties:

name=WebServer
version=1.0
author=Cristian Maglie <c.maglie@example.com>, Pippo Pluto <pippo@example.com>
maintainer=Cristian Maglie <c.maglie@example.com>
sentence=A library that makes coding a Webserver a breeze.
paragraph=Supports HTTP1.1 and you can do GET and POST.
category=Communication
url=http://example.com/
architectures=avr


How do I connect an 8x8 LED RGB matrix to an Uno?

Because you have, unfortunately, decided to buy a product without a datasheet (and the product description can't even decide if it's common anode or common cathode!), you'll have to find a product which is similar that has a datasheet, and determine by experimentation if the pinout matches.

For instance, this Sparkfun LED matrix looks similar. Take a look at the datasheet for an internal schematic and manually verify the pinout.

Once you know the pinout, you can begin to figure out how to drive it. There are many ways to drive large numbers of LEDs, one of the simplest of which is a bunch of shift registers.

Getting yourself a couple of 595 SRs and playing with the matrix (hint: try and get a single colour working first, then add the others) would be a good place to start.

Alternatively, the display description says that it is compatible with "Arduino RGB LED Matrix Driver Shield". That may or may not be true, but looking at a schematic of that board would give you insight into how to drive the matrix. I believe that board uses a DM163 8x3 CC LED driver chip, which seems to be perfectly suited to drive the matrix, but buying and wiring that chip up may be non-trivial.


Thermistor returns correct value on Arduino Nano, completely fails on Arduino Uno Wifi Rev 2?

The Arduino UNO WiFi Rev2 defaults to an internal analog reference of 0.55V where the classic (non-"Every") Nano defaults to the external VCC voltage as a reference, which is usually around 5V, often a little lower because of the diode it uses between USB and "5V".
Either you need to be using the same voltage reference by selecting a common one with analogReference, or you need to use different references and calculate differently (or provide different values to the thermistor library) according to each reference.
If you've been using the VCC on the normal Nano board, you could try analogReference(VDD); on the UNO Wifi Rev 2.  This isn't necessary a great way to do it (probably using internal references would be better), but it is a simple way to get similar results on a UNO Wifi Rev2 without changing more than a single line to set the reference.


Without seeing circuit and construction details and oscilloscope traces, it's difficult or impossible to say what the problem is.  It may be due to op amp instability due to a large capacitive load.  It may reflect a beat frequency between some sensor and MCU signals, or aliasing between 60-Hz noise and your data-conversion rate.

Regarding op amp instability, see for example the article Op Amps Driving Capacitive Loads, by Grayson King.  Here is a quote from that article:

  Q. How does capacitive loading affect op amp performance?
  A. To put it simply, it can turn your amplifier into an oscillator. Here's how: [...]

Rather than just connecting that big 3300 μF capacitor to the output pin, perhaps instead try attaching an Active Low Pass Filter to the output, or a unity-gain op amp followed by a Passive Low Pass Filter; etc.  Put big capacitors across power into the UV source and power into the sensor, instead of on the sensor output.

Regarding beat frequencies and aliasing, low-frequency oscillation like that seen in the trace may occur as a difference of two higher-frequency signals, or as a sampling artifact.  To check this out, attach an oscilloscope to the UV source and see if its power consumption oscillates; and/or try a more-rational sampling scheme than that shown in your code.

For example, instead of taking 8 readings within one millisecond in averageAnalogRead() and then waiting 100 ms, perhaps add a delay(1) inside the loop so that readings are spread out slightly more.  Remove the delay(100) from within averageAnalogRead().  Compensate by changing the other delay(100) in loop() to, for example, delay(191) or delay(193).  Try various delay amounts to see if they have an effect on the waveform.


Can I control a Z84 counter timer circuit with Arduino?

I wouldn't say it was a "bad" idea - pointless maybe, but not "bad". A good learning experience if nothing else.


Gnd pins at the power pin strip VS Gnd pin at the IO pin strip

In short, all the UNO ground pins are the same.

They are just there to make your life easier. At the end of the day, GND is GND. There is no technichal difference. Just note that is is sometimes better if you share the 3 GND ports. Overloading a port might damage it. Check the datasheet for current limitations of the pins.

EDIT

The pins (literal pins of the IC) themselves are also different on the ATmega IC.


Breadboard-to-Arduino wiring with flat flex cable assemblies?

Search for male-male jumper wire. Some of what you'll find is individual wires but there are also many that are connected together and you can rip off the width you need.

Here's one from Adafruit but there is no shortage of them on ebay/amazon.


How to use ATtiny pins that are usually 'reserved' for chip programming?

You can just normally use all pins except for the reset pin (pin 0). When you want to program the Attiny, you just connect the programmer. It will reset the Attiny through the reset pin and put it into ISP programming mode. At that point your code hasn't run.

Note: If you want to program the Attiny while it still sits in its circuit, you have to be careful, that the connected circuit does not disturb the ISP communication. The safest way is to disconnect the Attiny from its circuit and then program it.


Buy an external voice modem with a RS-232 connection. Connect it to a RS-232C shield. Use AT commands to dial numbers and pick up calls. Use voice AT commands to transmit or receive audio.

Never attempt to connect the telephone line directly to an Arduino since, yes, you will fry it. The voltage is all wrong in the first place, and goes even higher when the phone line rings.


Can I check if a message has been sent successfully using Radiohead_ASK?

There is no concept of "did the packet arrive", only "did it get sent" - and by "sent" I mean the data squirted out of the data pin for the attached module to send.

These 433MHz modules are dumb. Very dumb. You toggle the transmitter's pin high and low and the receiver sees that toggling, if it is in range, and toggles its output pin to mirror the signal.

The only way you can know if the packet arrived is if the receiver also has a transmitter and the transmitter also has a receiver. When a message arrives at the receiving node it sends a message back to the transmitting node to say "I got it". That takes a lot of work to get right, though. Especially since the original message may have arrived fine, but the acknowledgement didn't, and all sorts of horrible things can happen if you don't handle packet sequencing right.

Better is to pick a better module that does all these things for you, such as the nRF24L01+ with Auto-ACK turned on.


Arduino doesn't boot unless I short USB pin 1-2 (VCC/Data -)

When you plug the board in, the computer enumerates it. The normal device descriptor (IIRC) requests 50mA. If you are (as you most likely are) drawing more than that then the computer is quite within its rights to turn it off.

By shorting those pins you are preventing it from enumerating, so the computer doesn't know the requested amount, so it assumes (probably) 500mA.

You can achieve the same effect by using a cable with no data wires in it.


The part of your code that prints data to the serial looks like this:

void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.println(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}

The bug is in the Serial.println(angle); line. The println method inserts a "newline" character at the end. Try changing it to Serial.print(angle); so there is only one "newline" character.

void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.print(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}


if (digitalRead(exhaustpin) == LOW) {
    static unsigned long interval = millis();
    if ((millis() - interval) >= 600000) {
      digitalWrite(coolerpin, LOW);
      digitalWrite(exhaustpin, HIGH);
      // after the starting of exhaust fan it wait for 10 minutes, then it turns on
      // the cooler and turns off the exhaust fan
    }
  }

interval is only ever set once. So 10 minutes after it is first set it will remain over 10 minutes.

The simplest fix is to set interval to millis() when you set exhaustpin to low:

if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH)) {
  digitalWrite(exhaustpin,LOW );
  // if temperature increses above 30 the exhaust starts to work
  interval = millis();
}


The problem is that servo1.write(90) does not do what you think it does.

servo.write(angle) tells the servo to go to that position, not to move by that many degrees. What you need is to set one angle when the button is not pressed, and a different angle when the button is pressed.

Normal hobby servos can move about 180 degrees. Where 0 is depends on how the servo horn is positioned. Which direction of rotation is positive depends on the manufacturer.

try something like this to set one position when the button is pressed and a different one when it is not:

if (button1State == LOW);{
    servo1.write(45);  // move servo
}
else {
    servo1.write(135);
}


Atmega328p and cp2102 with error avrdude: stk500_getsync(): not in sync: resp=0x00

Researching a little and found the solution! In addition to capacitor 104, its necessari need to add a 10k resistor by connecting the 5 volts to pin 1.

This is the link of the GitHub project where I found the solution with the assembly scheme, I hope this helps somebody else!

https://github.com/leonvandenbeukel/Arduino-on-a-breadboard/blob/master/README.md


/*
HEADER TEXT
GOES HERE
*/
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup()
{
  // Serielles Interface initialisieren
  Serial.begin(9600);
  // SPI initialisieren
  SPI.begin();

  mfrc522.PCD_Init();

  // Für später
  // pinMode (2, OUTPUT);
}

void loop()
{
  // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
// String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
// byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

  // Nach neuen Karten suchen.
  delay(250);
  if ( mfrc522.PICC_IsNewCardPresent())
  {
    delay(250);
    mfrc522.PICC_ReadCardSerial();
     // Eigene UID bilden. Dazu nehmen wir die 4(7)Byte Hex UID aus Block 0 und quetschen sie in einen schönen String.
 String uID = String(mfrc522.uid.uidByte[0],HEX)+String(mfrc522.uid.uidByte[1],HEX)+String(mfrc522.uid.uidByte[2],HEX)+String(mfrc522.uid.uidByte[3],HEX);

  // PICC Typen
 byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);

    // Debug Ausgabe
    Serial.println();
    Serial.print("Die Kartennummer lautet: ");
    Serial.print(uID);
    Serial.println();
    Serial.print("Picc Type: ");
    Serial.println(mfrc522.PICC_GetTypeName(piccType));
    Serial.println();

    // Überprüfe auf unterstützten PICC Typ und noch mehr Debug Kram
    if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI && piccType != MFRC522::PICC_TYPE_MIFARE_1K&& piccType != MFRC522::PICC_TYPE_MIFARE_1K) {
      Serial.println("Diese Tech-Demo benötigt MIFARE Classic Karten.");
      return;
    }

    // Den UID String Verglichen und eine entsprechende Aktion ausführen
    if(uID=="myUIDforStuff") {
      Serial.println("Access granted");
    }
  }
}


Issues with connecting XBee to Arduino Uno R3

I am slightly surprised that you can actually talk to the XBee from your PC over USB with the XBee in the shield. XBee shields are generally designed for the XBee to be used by the Arduino only. The fact that you can actually talk to the XBee from the PC using X_CTU with the XBee in the Arduino shield, by holding down reset, seems to either be a quirk or a feature of the shield1.
Generally to use X-CTU to talk to the XBee, one would use an XBee explorer board or a Development board. One would configure the XBee completely in the Explorer dongle and then transfer the XBee to the shield for the Arduino to use it.
See the thread on the Digi forums, xbee s1 xctu arduino:

The shield is not design for writing and reading firmware to and from
the XBee module. It is only designed for basic two way communications.
If you want to read or write firmware to the module, you need to use a
board that is designed for it such as the XBIB boards from Digi.

See also Can an XBee be programmed with an XBee Shield.
However, hopefully someone with more knowledge of the internals of an Uno and XBee shield than I, could explain the actual electrical reasoning behind this issue. I have attempted to explain it below in the footnote.

1 Having said all of that, looking at some of my XBee shields, a couple have a microswitch, that enables the XBee to talk to either the Arduino or the USB, but not both at the same time. So, I guess that the need to hold the reset on your shield is because you do not have such a microswitch.
So the reason being, is that the Arduino and the USB can not talk to the XBee at the same time, as there would be conflict on the Rx and Tx serial lines - see this thread, UNO + Sparkfun's Xbee Shield Always Reset if Receiving Data From X-CTU Terminal which hints at the same thing. Two comments of note from that thread are:

It would be a lot simpler to debug the issue if you put the switch in the other position, and used SoftwareSerial to talk to the XBee and Serial to talk to the PC. Using one port to talk to two devices IS going to frustrate you no end.

and

Note that a communication application connected to an arduino that opens a com port, sends data, then closes may cause the arduino to reset.

As a (really wild) guess, I would imagine that the USB-to-TTL IC's DTR line, or equivalent (?), is [logically] tied to the Arduino's RST line, so that if the PC tries to communicate to the XBee, it ends up resetting it, rather than signalling to the XBee that it is ready to communicate.
Note: The USB-to-TTL IC could be a FTDI, ATmega 4U2/8U2/16U2 or an FTDI clone, depending on the variety of Uno that you possess.
Addendum
I do wonder why the switch is there, if it doesn't end up working correctly. Regardless, I would still get a $3 explorer board clone to use with X-CTU. Be careful which one you buy as not all of them work with OS X, if you use a Mac, see the end of USB-TTL interface devices on OS X. That explorer,  XBee USB Adapter Bluetooth Bee FT232RL USB to Serial Port Module for PC Arduino, is good value for money and compatible with WinTel, LinTel and OS X machines:


A more sophisticated version of @MikaelPatel's techique is not to store the individual counts, but to store a derivative:

Reserve a block of storage with (say) 8 counters. Each counter has as many bits as necessary to store the largest value - but see below for what "largest" means.
Each time the count goes up, write into the next counter along (modulo the number of counters).
But don't write the value of the counter, write the value divided by the number of counters - counter/8.
Here's the trick: while that looks like you're losing precision, you're not - because the counter location is information too! In fact you're gaining size.

It's best shown with an example. For ease, I'll assume an 8-bit counter, and only 8 counters:

0000: 03 03 03 03 03 02 02 02

Assuming that everything started at 00, that means that it took 8 counts for them all to get to 01, a further 8 counts for them all to get to 02, and only 5 counts to get the first 5 to 03. That's a total of 8+8+5 or 21.

At boot time, look for where the number sequence goes down. That's your current buffer position for future updates, plus the information for the current value:

CurrentCount = [Smaller number] * [Number counters] + [Number of larger];

Once you've worked it out, keep the current value for incrementing, and the buffer pointer for where to store the next count.

Advantages:

A. You write as often as you would storing a counter - but in different locations, spreading the load.
B. Each location (8, 16 or 32 bits) can store a certain maximum - but the total maximum is a factor of Number of Counters larger than that!

Odometer manufacturers use this exact technique to store the current mileage in digital dashboards - they have a legal requirement to maintain the correct number. They only use 16-bit counters (which would overflow after 65,535 miles), but then they use 16 counters, for a total mileage maximum of over a million. Each location only gets written every 16 miles, and they don't need to use 32-bit locations.


What background do I need to have before starting Arduino?

I am a Electrical technician and bought the starter kit from the Arduino team for my 13 year old son. My plan was to try the kit to teach my son about electronics.

The end result is that he is the one showing me new stuff.

In my opinion, you do not need any special background before starting with Arduino. You should have a interest in learning something new, and in learning about electronics. To get started, buy a tutorial book and a starter kit. (Many starter-kits comes with a tutorial book) When you have gone through the book, you will have some basic knowledge and a base to continue learning from.

Good luck


Door sensors on every cabinet in the kitchen

Touch less sensors (IR, magnetic hall), detecting drawer state.

1pc Arduino with I/O expanders to increase I/O ports.


Pass custom element of an array from an inherited class to main sketch

After reading comments i got some more clues where to search and indeed the problem was somewhat in the inheritance and how i was calling the functions. This post helped me find the problem.

I forgot to post the piece of code where i was creating the patterns in the Main Sketch, this is how it was initially:

Pattern ledPatterns[NUM_PATTERNS];
ledPatterns[0] = TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
ledPatterns[1] = TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

...
ledPatterns[p].Tick(millis());
...

When i later called ledPatterns.Tick (the function that modifies the values, the function actually being called was the parent and not the child. Thus the unexpected result.

This is how i should have been initializing the patterns, since they are inherited:

Pattern* ledPatterns[NUM_PATTERNS];
ledPatterns[0] = new TestPattern(NUM_LEDS, "Test Pattern 1", TestPat, 0, 0);
ledPatterns[1] = new TestPattern(NUM_LEDS, "Test Pattern 2", TestPat, 0, 1);

...
ledPatterns[p]->Tick(millis());
...

Sorry for the huge confusion, i thought the problem was in a completely different part of the code


Most of what follows has already been covered in previous answers. I am
posting this nevertheless because I feel no answer so far makes the
whole story clear enough. Let me break down the question into two
sub-questions.

1. How can I get non-ASCII characters correctly print on the serial monitor?

The answer is simply send them as UTF-8.

That's really all there is to it. The serial monitor expects you to send
UTF-8, and it will print the characters correctly only if you use this
encoding. But that brings the second question:

2. How can I get the characters as UTF-8 in my Arduino program?

Here you have several options:

Option 1: encode them yourself

For example, the Greek letter “μ” (U+03BC) in UTF-8 is (0xce 0xbc). You
can send those bytes explicitly, like

Serial.write(0xce);
Serial.write(0xbc);

or, more comfortably, like

Serial.print("\xce\xbc");

The second syntax is more convenient because it allows the character to
be embedded within a longer string.

Option 2: let the Arduino IDE encode them

If you can get the characters in the IDE's editor window, either with an
appropriate keyboard layout or by copying and pasting from another
application, then you can use them as is in the string:

Serial.print("μ");

The editor will save the source code as UTF-8, and those UTF-8 bytes
will go undisturbed from the source file to the compiled program, to the
Arduino memory, to the serial port, and finally to the serial monitor.

This option is the best for readability. However, it is somewhat
fragile: if the source code ever gets re-encoded (e-mail clients and
servers sometimes do that), then the resulting program will not work as
expected.

Options 3: let the compiler encode them

You can ask the compiler to do the UTF-8 encoding for you with the
syntax

Serial.print(u8"\u03bc");

Here, the escape sequence \u03bc is a way to represent the Unicode
character U+03BC (i.e. “μ”), and the u8 prefix means that you want the
string as a byte array encoded in UTF-8.

Note that, in practice, the u8 prefix is not needed, as the gcc
compiler assumes UTF-8 by default. I would keep the prefix anyway
because it doesn't hurt to make the encoding explicit, and it may avoid
angering some language lawyer...

Note also that the syntax above only works for characters U+0000 through
U+FFFF, i.e. the basic multilingual plane. For other Unicode characters,
you have to use the syntax \U + 8 hex digits. For example, the
character “” (U+1F60E: smiling face with sunglasses) can be printed
with:

Serial.print(u8"\U0001f60e");

Clarification about UTF-16: A common misconception has it that with
\u you write the characters as UTF-16 code units, and with \U you
write UTF-32 code units. But it is incorrect:
both syntaxes are used to describe a
single character (technically, a code point), irrespective of the
encoding. Since the UTF-16 encoding for “” is (0xd83d 0xde0e), one
could be tempted to write

// Write as UTF-16 code units in the source code.
Serial.print("\ud83d\ude0e");  // WRONG

but then the compiler rightfully complains

error: \ud83d is not a valid universal character
error: \ude0e is not a valid universal character

So forget about UTF-16. There is no UTF-16 involved anywhere, except in
the internal representation used by a Java widget used to implement the
serial monitor, which is a completely irrelevant implementation detail.


How to send and receive multiple integer values through serial comm for Arduino Micro and HC05 bluetooth?

Try Google Protobuf it's really awsome. I use it every time when I connect C# app to STM but it can be used in this case as well. U use Protobuf to encode your message and COBS do remove zeros from message so you can slap it on the end to know when the packet ends


Option #2 can definitely work, it is based on a widely adopted side effect of human vision called Persistence Of Vision, abbreviated with POV, which is used in Television, LED cubes and many other display devices.

You SHOULD notice no flickering if you manage to keep a refresh rate above 24 FPS (Frames Per Seconds or full refreshes), but not all human being are the same, that's why we tend to aim at 60 or 100 FPS to ensure flickering is not perceivable by anybody.

What you WILL notice though is a reduced brightness as each LED will be turned on only for a fraction of time.

So, naming your pins as COL1 to COL3 and ROW1 to ROW3, you can refer to the following schematic:

simulate this circuit – Schematic created using CircuitLab

You can further extend your option #2 by using an external IC, commonly referred as LED drivers: not something you need unless you get short of outputs.


How to compile Arduino ESP8266/32 on CI/CD (CLI shell cmd) platform?

Easiest answer: Use PlatformIO. (Yes this answer is technically an advertisement, but it is the correct solution here.).

Why not the others?

makeEspArduino is dependent on GNU make, hard to make modification to, hard to get support for when something goes wrong
Visual Micro Arduino is Visual Studio extension, thus native to Windows

Why PlatformIO?

On the other hand, PIO is just a framework written in python2, runs on Windows, Mac & Linux alike and supports tons of boards and frameworks. Not only is it OS-agnostic but it also IDE agnostic. It exports project files for Eclipse, Visual Studio Code, CLion, Visual Studio, Sublime, Atom and other IDEs. The Arduino IDE will always be only a (bad) syntax highlighter.

Support boards (479 of them) range from Arduino Unos to ESP8266/ESP32 over to STM32 and nRF boards. It's also possible to compile one firmware for different environments (board), so with a well-written firmware, PIO can generate firmwares for multiple boards and frameworks alike. Frameworks include Arduino cores, ESP-IDF, STM32HAL and more.

To create a new project, you'd do

user@somefolder/$ pio init --board=nodemcuv2 --ide=vscode

To compile from CLI, you just have to execute the run target:

user@somefolder/$ pio run

To upload you'd just

user@somefolder/$ pio run -t upload

With optional --upload-port=/dev/ttyUSB0 or alike. Updating wirelessly over ArduinoOTA is also supported.

Video: https://www.youtube.com/watch?v=EIkGTwLOD7o

Documentation: http://docs.platformio.org/en/latest/


Smallest package possible reading microSD

SD card need 3.3v for power and logic level. So most breakouts have a buffer chip to convert the logic levels from 5v to 3.3v.

PS, you could use an microSD to SD adapter, and solder some wires to its pads, if you are unable to solder the tiny pins on the part you ordered.


Can't get call / message from A7 gsm+gprs+gps module

Increase your second delay to 2000 (ie. 2 seconds).

delay(2000);


If Digispark Pro clone is not recognized, you can try to use/upload .ino programs via ArduinoISP.

note use in File -> Preferences -> Additional Boards Manager URLs:
http://drazzy.com/package_drazzy.com_index.json
instead:
http://digistump.com/package_digistump_index.json

(The first is AttinyCore by Spence Konde, the second is the normal Digistump AVR Boards)

Then selected Tools -> Boards Manager, and Find AttinyCore -> (Wait and Install).

Now you can upload File -> Example -> ArduinoISP on your Arduino connected in ISP mode with your ATtiny167.

Now select ATtiny167 Board, 16Mhz (External) and write bootloader with your Arduino connected in same manner ISP mode with your ATtiny167.

And now upload any .ino file for ATtiny167 in the same manner with your Arduino connected in ISP mode with your ATtiny167.


The relay module you have is this one from SainSmart:

http://www.sainsmart.com/arduino/arduino-components/relays/sainsmart-2-channel-5v-relay-module-for-arduino-raspberry-pi.html

The schematic is like this:

As you can see you connect VCC to +5V and IN2 to your IO pin.  Setting the IO to LOW will then turn on the LED and the optocoupler together.

But that's not the only way you can connect it up.

Connect VCC to the IO pin and IN2 to GND instead.  Then you set your output HIGH to turn it on.

The arrangement shown in the schematic is commonly done because some MCUs are able to sink more current than they can source thorugh an IO pin.  That is not the case with an Arduino which has symmetric IO pins that can sink and source the same amount of current.


It could be your JSON object capacity is too small because of string duplication when you deserialise it to print it.
You should try a capacity like JSON_OBJECT_SIZE(3) + 500 for deserialising, and see what happens.
Also, try: doc["rfid"] = str_rfid.c_str(); to see if that works better (CString instead of String object).
More information on object capacity can be found here; there's a calculator here.


Using NodeJS, socket.io and Adafruit HUZZAH CC3000 breakout board to control Arduino wirelessly?

I happen to have received the CC3000 shield yesterday and have been playing with it today...

What do you mean by "receive commands from a website"?

If you mean "can it serve a simple website and act upon HTTP requests" (e.g. requests to http://arduino.local/on would turn a lamp off and http://arduino.local/off would turn if off), then yes it can. You make the HTTP requests using javascript's XMLHTTPRequest if you want to be able to communicate from within a web page without having to re-render a page.

There is an example sketch of an HTTP server included in the CC3000 library that would get you started. Note that the example HTTP server sketch can only handle one HTTP request/response at a time.

You will obviously also need some way of controlling a relay of you want to control a lamp.

Update: Since you updated your question to include how you are currently communicating:

I'm not familiar with socket.io or Firmata, but I'm guessing socket.io is a way of getting your web client (browser) to talk directly Firmata which talks to your Arduino over the USB-Serial connection? If so, then I'm not sure if it's possible to use the Firmata protocol over wireless, but it is possible for the CC3000 to act as a generic TCP server and act on data that it receives wirelessly, so it might be possible to communicate between socket.io and the TCP server. The EchoServer sketch shows how to set up a TCP server to receive raw data.

If you're only turning a lamp on/off you basically only need to control 1 pin. Isn't Firmata a bit overkill for that? Be careful about sketch size. I'm not sure how big Firmata compiles to, but the wireless library with some kind or server is over 22,000 byes (of a possible 32,000) on an Uno, so you might struggle to fit both on.


Basic usage of Nick Gammon's Regexp library

You haven't defined any capture groups in your regexp.

The regexp [aeiou] will match any of those characters, but it won't capture them.  To capture you need to define a capture group which is a sequence of tokens surrounded by parenthesis.  For instance:

([aeiou])

In your test phrase "The quick brown fox jumps over the lazy wolf" that should match 11 times and capture each match, resulting in captures of e u i o o u o e e a o.

The reason why matching and capturing are two completely different things is so you can do things like [aeiou]([aeiou]) which would capture the second vowel in a two vowel sequence. In your example it would match the ui of quick and capture just the i.


A stepper motor doesn't have any mechanical "steps" as such. When powered off, a stepper is free-wheeling. When you power it up - energize a set of set of coils - the rotor will move to the nearest of several positions corresponding to whichever coils are energized. Thus, it doesn't retain its position across a power-down; your code has to "find it" each time. Usually that involves driving it until the attached mechanism trips an optical or mechanical switch, giving the software a reference-point. Your other option is to apply a holding current (less than the stepping current) to the presently energized coils and not completely power down the motor's power supply when the rest of the system powers down. The software would have to save the motor position before the power down in a non-volatile memory, such as EEPROM, where it can retrieve it again at the next power-up.


How to check whether my arduino-mega ADC is sampling correctly?

In this case the baud rate will be real bottleneck. You have to send from 110 to 230 bits per reading (1 start bit, 8bits data, 1 stop bit)*(3*2 spaces + 4-16 number characters + 1 line feed).

That means best case (all numbers are less than 10) 349 readings per second. And worst case is 166 readings per second (all readings are more than 999).

So it's about 10% probability to be sampled correctly.

You can check if the next time (with misleading name lastReading) is less than current time. That means you are already too slow.


Arduino Leonardo keyboard.print keeps printing equal sign

The method write with one parameter takes char not string. Use write('W'), not write("W");


Follow up question to Calling a timer when a button is pushed

Yes, it is because in timer() and timer2() you busy-loop with while until the condition is not met. Hence, when buttonState2 is HIGH, your code will execute timer2() until the condition of the while loop is not met. You are effectively doing a delay.


The truth is, the Arduino Wire library sends the data only if endTransmission is called. Until then it collects the data in TX buffer. The version of the write function used in your snippet adds a byte to the TX buffer.

With I2C usually the first byte written is the address of the register to write. Then the data follow. In case of the first part in your snippet the data are only one byte long.

In the second part, first the register address is sent with write and then the data from this register and 3 following registers are requested.


With a current rating of 0.68 A at 12 V you get the normal power requirement of 8.6 W for a 7Kg.cm torque.

If, for any reason, you stall the motor, your driver must be capable to output 2.2 A or 26.5 W to avoid a permanent damage.


How do I interface two Arduino boards so they act as one with double the code space?

There is no simple way to combine multiple boards into a unified system. What you will need to do is delegate certain tasks to each board and then have them communicate via SPI, I2C, or UART between a master board and each slave board in the system. The master system will then present the interface of the system as a whole via serial, wifi, console, etc.


the timer will set the Timer Interrupt Flag (TIFR0 register)
The ISR will be called, and the flag will be cleared
you do some long calculations or something
the timer will match OCR0A, and set the interrupt flag again.
you calculations are done, and the ISR function will end.
the uC will jump back to the main loop code, and execute 2 1 instructions.
The uC will see the flag, and call the ISR again. As per step 2.

PS please note that by default the ISR macro will turn off global interrupt (cli) at the beginning of the function, and set it back at the end. You can re-enable interrupts inside the ISR, but you have to be very careful here, as interrupts can be nested, and cause stack-overflows.

You can re-enable interrupts inside the ISR, but that only means other interrupt may interrupt this ISR, but never the same vector. (i.e. only one ISR per vector can run at the same time). So in your case the timer ISR can't be interrupted by the same timer interrupt.


The M0 boards use a SAMD chip. It has no EEPROM. To store data without additional hardware like external EEPROM or SD card, you can use the flash memory of the SAMD. But it has a drawback of limited count of writes to flash memory.

An EEPROM emulation library exits. It uses the flash memory, so the drawback of limited writes, applies. I used it, it works. The library is almost official. The author is Arduino's coworker.


First of all use the event function server.on with a path that corresponds to your function and use a url like this:

192.0.2.2/recordnumber?num=100

With a url parmeter for your number. Your code might look like this:

At the top:

int nums_size = 0;
const int nums_max = 128;
int nums[nums_max];

In setup:

server.on("/recordnumber", [](){
    int num;
    if(server.hasArg("num")) {
      String num_str = server.arg("num");
      if(num_str.charAt(0) == '0') {
        num = 0;
      } else {
        num = num_str.toInt();
        if(num == 0) {
          server.send(400, "text/plain", "not a number");
          return;
        }
      }
      if(nums_size < nums_max) {
        nums[nums_size++] = num;
        server.send(200, "text/plain", "saved");
      } else {
        server.send(500, "text/plain", "full");
      }
    } else {
      server.send(400, "text/plain", "bad params");
    }
});


formatting of IPAddress via printf(...) family similar to Serial Object

Whereas KIIV's answer solves your problem, it does not address some very
interesting parts of your original question:

  I am not sure why Serial.print() is able to convert IPAddress to a
  reasonable human readable representation

This works thanks to a couple of abstract classes in the Arduino library
called Print and Printable. A Print object is anything that can
output text, like a serial port, a network connection or an LCD. A
Printable object is anything that can be converted to a text
representation and sent through a Print object.

From Print.h:

class Print
{
    // ...
    virtual size_t write(uint8_t) = 0;
    // ...
    size_t print(const String &);
    size_t print(const char[]);
    size_t print(unsigned int, int = DEC);
    size_t print(const Printable&);
    // ...
    size_t println(const String &s);
    // ...
};

In other words, in order to create a Print, you only have to implement
write(uint8_t), which should output a single character. Then you get
all the print() and println() methods.

From Printable.h:

class Printable
{
  public:
    virtual size_t printTo(Print& p) const = 0;
};

This means you can make any object Printable by implementing
printTo(Print&).

From IPAddress.h:

class IPAddress : public Printable {
    // ...
};

This means IPAddress objects are Printable: they know how to print
themselves into any Print. You can find the implementation of
IPAddress::printTo(Print&) at the end of
IPAddress.cpp.

Thus, to answer your question, Serial.print() does not really know how
to create a textual representation of the IPAddress, but IPAddress knows
how to send itself through Serial, or any other Print object.

  I want to somehow leverage that functionality [...] there must be some
  relatively simple way to utilize the functionality that Serial.print()
  provides but somehow channel it to an sprintf() call.

The functionality is not provided by Serial.print(): it's the fact
that the IPAddress is Printable. In order to leverage that, you have to
create a Print object. You cannot use sprintf() for that, but you can
create a Print object which behaves like sprintf() and writes into a C
string:

// Write into a C string (a char array), a la sprintf().
// Warning: there is no check for buffer overflow.
class StringPrinter : public Print
{
public:
    StringPrinter(char *buffer) : buf(buffer), pos(0) {}
    virtual size_t write(uint8_t c)
    {
        buf[pos++] = c;  // add the character to the string
        buf[pos] = 0;    // null perminator
        return 1;        // one character written
    }
private:
    char *buf;
    size_t pos;
};

which could be used like this:

char buf[16];
StringPrinter(buf).print(ip);

For the sake of simplicity, I would generally prefer the straight
sprintf() solution. However, if you are short on flash, the code above
is likely to be smaller, as sprintf() is large and you are very likely
to be already using Print in your program.


I2C comunication, ESP->Nano on endTransmission no ACK fron nano

I'm a fool, I tried to detect other devices in the setup function before the Wire.begin(PIN_SDA, PIN_SCL,  I2C_MASTER);
I Found it only because of you. The rubber duck. I started to write the program down to post it here and bingo.
That was the reason why the master had the "NACK" answer. The master was not started yet.
Thank you


@Jot commented to use the Keypad Library. Which I got to work using the tutorial. Took a few minutes to set up.


Feeble click in relay but it doesn't get activated when connected to Arduino circuit

You need to join the ground of the external supply to the ground being supplied from the Arduino.  The 12V supply must be capable of at least 100ma

There appears to be a transistor and resistor on the board.  This is probably to drive the relay coil from the Arduino.  However, I would need to look at the circuit diagram of the board to be certain.  Can you supply images of the copper side and component side of the board to see what the connections are.

Ideally the circuit diagram from the manufacturer would be even better.


How can I program RFduinos and how can I connect them with Bluetooth?

I am starting on a similar project (without the Dev Kit).  Hooking the Bluetooth module to the RFduino is pretty straight forward, PWR to PWR, GND to GND, remember to cross the transmission wires: TX to RX & RX to TX.

In your void setup(), you need to start the connection:

Serial.begin(9600); // check your documentation to see the baud rate

In your void loop(), read or write to/from the bluetooth connection with serial write/read. Serial.read() or Serial.write()

Remember that Bluetooth is a communication protocol, not a controller.  You don't mention WHAT you are connecting your RFduinos to using Bluetooth. You still need a controller capable of sending a signal to light up the LEDs using Bluetooth.


What is the difference between Serial.write and Serial.print? And when are they used?

Serial.write is more down to earth , it is simple and fast, it is made to talk binary, one byte at a time.
example:

Serial.write(0x45);   // will write 0100 0101 to the cable

Serial.print in the other hand is more versatile , it will do the conversion for you from ASCII to binary it also can convert to BIN/ HEX/OCT/DEC but you need to specify a second argument like so

Serial.print(76, BIN) gives "0100 1100"
Serial.print(76, OCT) gives "114"
Serial.print("L", DEC) gives "76"
Serial.print(76, HEX) gives "4C"

more examples with visual serial output :

Code:

  Serial.write(0x48);   // H
  Serial.write(0x45);   // E
  Serial.write(0x4C);   // L
  Serial.write(0x4C);   // L
  Serial.write(0x4F);   // O

SERIAL OUTPUT :

Code:

  Serial.print("HELLO");

SERIAL OUTPUT :

Serial.println() in the other hand will add end of line 2 bytes 0x0D and 0x0A as you can see in the frame

Code:

  Serial.println("HELLO");

SERIAL OUTPUT :


You wrote:

I wrote out a function to allow me to grab a piece of the string 32
bits at a time and convert that into a number while using an offset

This function is almost correct. Try this:
uint_fast32_t get32BitInt(const char *data, int offset = 0)
{

  uint32_t payload = 0;
  for (uint8_t i = 0; i < 4; i++)
  {
    payload <<= 8;
    payload |= data[i + offset];
  }
  return payload;
}

Compared to your version, the differences are:

It reads 4 bytes instead of 8, as 32 bits are four bytes.

For each byte being read, it shifts the payload by 8 bits (i.e. one
byte) instead of zero. Shifting by zero has no effect.

It uses |= instead of +=: just a micro-optimization for the sake
of 8-bit MCUs. It shouldn't make much if a difference on a 32-bit
micro.


powering arduino with a voltage divider to increase lifespan

Terminating voltage by dropping it over large power resistors is a bad idea, efficiency wise. There are better options.

Switch-mode Buck (=step down) converters are usually far more efficient than linear regulators. A linear regulator dumps the excess voltage in a resistor which converts the energy mainly into heat. A switch-mode converter works by switching on/off an inductance at the right time, which is far more efficient.

For step-up/step-down DC-DC converter theory look here, here and here. For a comparison for switch-mode against linear regulators look here.

A step-down converter module like the ones with a LM2596 should be good enough for you. See here on ebay.


How to increase Arduino's memory to save Dot Matrix Library?

Use a different Arduino or Arduino-clone with more flash memory
Store the character bitmaps in external EEPROM (example)


It is not possible to trigger an interrupt when an analog input has reached a threshold on any tinyAVR or megaAVR. It is possible to trigger an interrupt when an analog input of an AVR XMEGA with the event system.

It is possible to use the built-in analog comparator on the ATmegaXX8 and ATmegaXXU4 in the Uno, Leonardo, and comparable boards to trigger an interrupt when an internal or external threshold has been met. It is only possible to compare to an internal threshold on the Mega, Mega 2560, or comparable boards since the pin for the external threshold is not broken out, although actual breakout boards for the ATmegaXXX0/1 will have the pin broken out.

In all cases, examine the appropriate datasheet (in particular the "Analog Comparator" section) as well as the pin mappings on the Arduino website for full details.


How the light brightness stays constant when we increase the frequency of stroboscope

To keep the same brightness, you have to keep the same duty cycle (percent of on time over off time).  So to change the rate without changing the brightness, you have to increase
delayMicroseconds(onTime) by the same percent you increase delay(strobeDelay).  But note that as you go slower, the on time will be too long to freeze the motion you are trying to study.  (If it's just for a party effect this may not matter.)


Serial communication between a single Android device and multiple Arduino boards

Use a third Arduino, which serves as a hub. It is connected to your Android and to all Arduino Uno devices you want to interface. It passes the commands to all Arduino devices, and the feedbacks to the Android device. You could use for instance an Arduino Mega, with the Android on Serial0, and the Arduino Uno devices on Serial1 and Serial2.


Arduino UNO with integrated ESP2866 wifi not working correctly

You are obviously currently programming the ESP8266, not the Atmega328p. The board seems to have DIP switches on it. With those you can control, which chip is connected to which. The product description has the following table
Connection  DIP
1   2   3   4   5   6   7
ATmega328<->ESP8266     ON  ON  OFF     OFF     OFF     OFF     OFF
USB <->ATmega328    OFF     OFF     ON  ON  OFF     OFF     OFF
USB<->ESP8266 (Update firmware or sketch)   OFF     OFF     OFF     OFF     ON  ON  ON
USB<->ESP8266 (communication)   OFF     OFF     OFF     OFF     ON  ON  OFF
All independent     OFF     OFF     OFF     OFF

If you want to program the Atmega328p on it, you need set the DIP switches to the combination "USB <-> Atmega328". Currently you most likely have the combination "USB<->ESP8266 (Update firmware or sketch)", which means, that the ESP is connected to the USB chip (and thus to the PC) for programming. For blinking the Arduinos buildin LED you need to program the Atmega328p.

About the blink sketch: In the tutorial video he programs the ESP. But in the blink example he changes the delay time to 5000, which would mean on and off times of 5s. The LED, that he is pointing to, is blinking much faster, though he doesn't address this. I think he actually has the standard blink sketch on the Atmega and only pretends (or just didn't notice) that this happened due tp his programming. As you don't see a blink with the ESP, but with the Atmega, I would guess, that the LED marked with L is connected only to the Atmega (like on a normal Uno) and the ESP doesn't have any LED to blink connected. So everything is actually working as expected, the tutorial was just bad at that point.


RS-232 logic uses a negative voltage typically from -3 to -25V to represent a logical high and a positive +3 to +25V to represent a low. On the flip side TTL used on the AtMega uses +5V or +3.3V as a high (or VCC) and 0V as a low. Read more

Other than that the signals are the same logically so all that is needed is to invert the RS232 from -/+ ~12V to 0-5V using a simple converter.

Possibly the easiest approach is to use another Arduino Uno as a programmer, which needs 3 pins, TX, RX, and RESET. This tutorial seems to have some success. Check out "programming an Arduino with another".


Serial Communication, if statement not working

You are using Serial.println() to send the message. That function will add the combination \r\n as line ending to your message, which are the ASCII codes for return carriage and newline.
In your receiving code, you read until \n, so your message now reads "0\r", which is of course not equal to "0". Thus the if condition will never trigger.
When using msg[0] == '0' you are taking the first character out of the string and compare that to the character '0' (especially note the difference between "0", which is a string, and '0', which is a single character). Since you are only using the first character of the string, the \r is out of the picture; you aren't using it.
What to do now?

You could send your message only with the \n character as line ending. For this only use Serial.print() instead of Serial.println() and add the line Serial.print("\n"); directly after you send your message.

You could write your own read-until code and just ditch every occurrence of the \r character.

You can use msg.trim() to remove any white space characters at the start or end of your string, including the \r at the end. Then you can use the code, that you already wrote.

Note, that using Strings on an Arduino is mostly considered evil. Especially if you want to use the code for a longer period or you are using String very often. The memory for a String is allocated dynamically, which can easily lead to heap fragmentation. For a better and longer explanation, look at The Evils of Arduino Strings, a blog entry from Majenko, who is one of our biggest contributors here.


Sending mouseX and mouseY from Processing to Arduino

Since you can't use the serial monitor to "see" the incoming data from Processing, here are 2 test sketches that may help you determine if data is received on the Arduino.

Upload the Arduino sketch first. Leave the serial monitor closed. Now run the Processing sketch.

I'm using frameRate(1) in the Processing sketch to send the data once per second, so the mouse X/Y values in the Processing window will be slow to update.

You should see the LED on the Arduino flash on then off quickly as the data is received. If you have a I2C LCD available, you could connect it to the Arduino and print out the incoming data.

As chrisl mentions in the comments, there is still much work to be done to get the raw data in the format you require.

Arduino

int x = 0;
const byte ledPin = 2;

void setup(){
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  if(Serial.available() > 0){
    x = Serial.read();
    digitalWrite(ledPin, HIGH);
  }
  else{
    digitalWrite(ledPin, LOW);
  }
}

Processing

import processing.serial.*;
Serial port;
void setup() {
  size(500,300);
  background(148);
  try{
    port = new Serial(this , Serial.list()[0], 9600);
  }
  catch(Exception e){
    System.err.println(e);
    e.printStackTrace();
  }
  frameRate(1);
}

void draw() {
  background(148);
  //@chrisl comment: Finish your data, that you send with \n (newline).
  port.write(str(mouseX)+' '+str(mouseY) + "\n");
  text(mouseX,250,50);
  text(mouseY,250,70);
}

EDIT

Here is a second Arduino sketch that will display the mouse X/Y values sent from Processing on a LCD. You could change the Processing sketch's frameRate() value to 10.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

char inputBuffer[32 + 1];

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup(){
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
}

void loop(){
  if(Serial.available() > 0){
    lcd.print("                ");
    Serial.readBytesUntil('\n', inputBuffer, 32);
    lcd.setCursor(0, 0);
    lcd.print(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}


Why is the output on the MOSI line shifted 1 bit over from what I commanded?

CPOL is clock polarity, and CPHA is clock phase.

The SPI modes are:

Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)

Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)

Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)

Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

According to your datasheet:

  Data from the SDIN line is clocked into the 24-bit input shift register on the falling edge of SCLK.

Judging by the diagrams on the datasheet, Mode 1 is what you want. You want the trailing edge of high to low.

More information at SPI - Serial Peripheral Interface - for Arduino


Replacing the Voltage regulator of a fried Arduino

I know it's an old thread, but others are likely to have this problem.  If you check the open source schematics, there are a couple of nearby capacitors that connect pin 1 (GND) to pin 2 (+5V) of the regulator.

I would check C2 and PC2 (top right of the diagram) as well as C1 (top left of schematic diagram), and any other components you can find that bridge the rails between +5V and ground.  Capacitors are more likely to fail shorted than many other components.  You will have to remove at least one pin of each capacitor to test it since you don't know where the short is, or you can simply remove capacitors until the short goes away.


How can i use a TFT Screen shield along with other sensors and transmitters

You need another layer! A breadboard shield - from the same source if you like - would seem the obvious answer.
Alternatively, take flying leads from the pins you are using to the screen & mount it elswhere, then connect the sensors.
LCD's use quite a few pins, you'll probably need to be creative with an Uno. I have one on a Mega, & have been there with the same problem!