Input 4-digit number using 4*4 keypad and show in serial monitor

keypad.getKey() is non-blocking as you can read here: it will return a value immediately, even if no key is pressed.  You have a for loop which will increment i each time, and you also increment it yourself. So what's happening is that your code is immediately making four readings, all of which are no-key-pressed so it doesn't store them, and then printing whatever happens to be in the myNum buffer.

Instead, you need to wait each time until a key is pressed, and only then move to the next digit. There are of course many ways you could do this.  I hope this is clear:

#include <Keypad.h>

int myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input

  for (int i = 0; i < 4; ++i){
    while((myNum[i] = keypad.getKey())==NO_KEY) {
      delay(1); // Just wait for a key
    }
    // Wait for the key to be released
    while(keypad.getKey() != NO_KEY) {
      delay(1);
    }

  }

  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}


Sampling rate of multiple analog pins on Arduino

1)  You only have one ADC on board and all the pins run through a mux.  You can only read one pin at time.  If you're willing to give up some resolution then you might can read a little faster but it gets tough.  What's worse is that when you are switching pins really fast it can mess with your readings so that for some things, especially when input impedance is high, you have to read twice and throw away the first reading.  So that essentially cuts your sampling rate in half right there.

2)  That may be doable.  Or at least something close to it.  You'd run in free-running mode and write a tight ISR to read the interrupt when the analog read is finished and record every other value and switch the pin every other time.  Theoretically you should get pretty close to 1kHz with 5 pins.  Maybe a little faster if you give up a little resolution.

3)  Those communications protocols run at light speed compared to the analog read.


Can I control two coreless DC motors using L293DD SMD IC?

Can the L293DD SMD IC be used to control these motors?

Yes

  Is there an alternate solution/circuit/IC which can minimize the size and area?

Any of the more modern MOSFET based H-Bridge drivers that exhibit far less loss than the antiquated l293d

  Are ESCs required for these small coreless motors?

No

  Can they be controlled directly via the L293DD (like normal motors)?

Yes

The L293 is old and, well, basically crap. For efficient battery based operation you realy need to be looking for something a little more modern and efficient. There's length to choose from - take a look on your favourite electronics supplier (which means not Amazon...)


SPI MCP23S08 to Arduino: strange stop/start behaviour

I have figured it out, lesson learned. I should have also drawn how my circuit connects to the Arduino, this would have probably then become obvious to me and everyone else.

Basically I had MOSI -> MOSI and the same with MISO -> MISO, rather than crossing them MOSI -> MISO respectively.

Circuit working fine now duh!

Face-palm!


How to avoid the code interrupting itself?

You can't use threads on an arduino, they don't exist. you can get some pseudo multitasking going with interrupts, but that is not necessary in your case.

You should be able to refactor your code to avoid using delays without much work. The arduino library provides millis() to keep tract of the time since the arduino was powered on in milliseconds.

something like this could replace all the delays in your code

static boolean state;
static uint32_t time;
if(time < millis()){
    time += delayFromPercent(percentValue);

    state = !state;
    if(percentage < 1.0) state = false;
    digitalWrite(in1, state);
}

Then, somewhere else place

uint32_t delayFromPercent(float percent){
    if(percent < 25) return 100;
    if(percent < 50) return 50;
    if(percent < 75) return 25;
    return 10;
}

alternately, if you don't really want the discrete steps, you could use this instead

uint32_t delayFromPercent(float percent){
    return max(10, 100-percent); // don't return less than 10ms
}

you could change it to react a bit quicker by comparing the time plus calculated delay now rather than when it last set the pin, but that strays farther from what your initial implementation would have done.

In any case, this code will should be able to switch pin in1 without making the rest of your code slow down, as long as the other code does not use delays either.


How to prevent the Serial Monitor from closing upon re-uploading sketch?

I assume you are uploading the code over USB - the same USB that you want to monitor for output from the sketch? If so, the serial monitor has to release the port for the uploader to be able to use it, and vice-versa, as your computer's OS will only assign a USB port to one application at a time.

It may seem like the IDE is one application containing an uploader and a serial monitor, but the IDE is not much more than a "pretty face" that runs separate compiler and uploader applications on your behalf.

Several work-arounds are possible (although I think a delay() statement in setup() is the clearest of the choices):

Add a delay statement in the setup function. If you must this, you can put it in main() just before the setup() call, but you'd take away a learning opportunity.
Use a separate hardware or software serial channel for the monitor which you could leave connected and wouldn't interfere with uploading;
Use the loop() function instead, and put a forever loop at the bottom to prevent it returning, thus making it a runs-once function.


problem in integrating the slave code in attiny 84

You are trying to compile the wrong program for the wrong chip.

The nice thing about the Arduino core library is that it enables you to
write code that is portable across various Arduino boards. However, this
library provides very limited access to the capabilities of the
underlying hardware. Then, it is quite common for users to mix Arduino
code with C statements that directly access the hardware registers.
Doing this provides full control over the hardware, at the cost of
reduced portability.

Just an example from your code:

SPCR |= bit (SPE);

This line is accessing the control register of the SPI port (SPCR means
“SPI Control Register”) in order to set to 1 the bit named SPE (for “SPI
Enable”). This is the “bare metal” way of turning on the SPI port.

Now, your problem is that, unlike the ATmega328P powering your Unos, the
ATtiny84 does not have a hardware SPI port. Thus the line above just
makes no sense.

The solution: you have to figure out some other means for your chip to
talk SPI. You could emulate it purely in software, but it would
certainly be more efficient to use the USI port. The USI (“Universal
Serial Interface”) is a multipurpose serial port found in many ATtinies.
It can be configured to do SPI, I2C or simplex/half-duplex UART.

Recommended readings:

AVR319: Using the USI module for SPI
communication, an
application note by ATmel
Using an ATtiny2313/4313 as SPI
master on the Arduino
Playground

You may be able to find ready-made libraries for doing this.


What is wrong with this processing code?

As @Matt said,

  The problem you have is not with the Arduino

Put if(port.available()>0) in the timer, or as event instead of void draw(). Furthermore, I can't found the calling of draw in your code.


Occasionally people do not realize how many platforms the Arduino paradigm has been ported to.  In almost all cases the ported to platform far exceeds the features found on an Arduino Uno.  So there exists a considerable amount of software that can not run on an Arduino Uno or on an Arduino Uno with out additional hardware.  But, usually, such software is surrounded by "text", "web-pages" and other "readme"  type files explaining the situation.

For the Arduino Audio library, the web-page says this:

  Audio

  Compatible with Arduino Due only

  The Audio library enables an Arduino Due board to play back .wav files
  from a storage device like an SD card.

  The Due uses the DAC0 and DAC1 pins to play sounds.


Is it safe to place a capacitor across vin and gnd?

I have a 3A fan hooked up to an ATX power supply in parallel with a transformer which powers my board through VIN/GND.

I don't entirely follow that wording. Please draw a picture.

  I have place a 470μF capacitor accross the Arduinos VIN and GND pins and it seems to have stopped the problem, but I'm not too experienced using capacitors. Is this an apropriate value? I'm not sure what difference it would make. And is this a wise move as I so think?

470µF is fine. In this situation the bigger the better. If 470µF fixes it then 470µF is fine. Don't be afraid of going higher though. I have 3,300µF capacitors here that are commonly used for similar purposes.

What you have implemented is called a reservoir capacitor and is a common use for large value capacitors like that.


The "Arduino" part of your schematic looks OK. 9 VDC to VIN on the Uno is OK. Connecting the MOSFET directly to the Arduino is OK.

Personally, I would connect a 1000 ohm resistor in series between the Arduino pin and the gate of the MOSFET. If you like to live dangerously like I do, and change wiring connections with power supplied to your Arduino, then a 1k resistor will limit the maximum current flow to around 5 mA. This is not going to "fry" anything if you inadvertently connect an output to power or ground.

The question about the L7805CV is off-topic, but a quick look at the datasheet suggests an input and output capacitor should be used.

I’m sorry to be the bearer of bad news, but the IRF540N is a poor choice as a MOSFET to use with a micro-controller. While it’s true that you are only drawing 60 mA, the VGS specified for this MOSFET is at 10 VDC, not the 5 VDC supplied by the Uno. A "logic level" MOSFET would be better suited for your application.

For more information regarding MOSFETs, please read: How to control a 12V solenoid valve with a mosfet?


The Arduino robot tutorials describe a cord comming with the official robot, now I'm confused

Usually, Arduino gives you the minimal board and sends you on your way. Reading over the instructions, I think they mean a cable that would have come with the IR sensor. That three-tone cord you see in the pictures are actually just three wires. You connect them as described if they came with the sensors. More likely, if they did not, you can use your own wires to connect these. Just be sure that you understand which is the ground (GND), power (+5V or some other +V), and signal. Usually, ground is denoted by the darkest color: black or brown; power is usually red, and signals can be any light color. USUALLY (READ about your device before you plug it in) ground and power are side-by-side for IR sensors, and signal is on the outside. Take a few minutes to Google up your device before plugging it in if you don't have documentation.

Good Luck!


You can only send and receive fixed length amounts of data with I2C. The master has to know how much to request from the slave - or the slave to accept from the master.

There's a number of ways around it though:

Splitting / joining.

The trick here is to split the data into packets and re-assemble it at the remote end.

For instance, you split your string into 16-byte chunks. Then you send each chunk separately. Prefixed to each chunk (so the chunk becomes 17 bytes) is a byte telling the remote end how many characters are in this chunk.  Any spare space in a chunk is padded with something (0x00 for instance) so it remains 17 bytes long in total.

two-stage transaction

In this method you first make a transaction which tells the remote end how many characters to receive in the next transaction, or retrieves the number of characters that need to be received from the remote end. The second transaction then receives (or sends) that specific number of characters.

If your strings are longer than the internal I2C buffer (32 bytes) then method 1 is probably the best way.

You can also combine the two methods so both ends know how much to expect to be transferred in total as well as how much of each packet is valid data. The sum of the second should match the first.


You should add pull-down resistors generally of 10k on the interrupt pin, this will resist the unwanted signals on that pin.


Wireless Sensor communication with 100Hz rate

Make one static tcp connection with a regular check and on error event to restore it in case it drops. Tcp must be able to run data at your rate.
If not, maybe the main arduino loop has delays in it.


Sending and receiving custom messages with Ardulink

you can read a complete (real project) example about how to receive messages from Arduino with Ardulink from here: https://github.com/openQCM

In general you can use a listener (digital, analog, and raw) to receive messages from Arduino. A raw listener receive all messages received from Arduino, so you need to implement code to filter the messages you are interested in. Digital and Analog listeners receive events from digital and analog PINs.

The sketch in your question isn't the original sketch you can find in Ardulink distribution. That sketch was written to manage the OLED on the ChipKit shield I have. You have modified the sketch to manage your LCD.

Actually you can send successfully messages from an Ardulink based application (as Ardulink Console) to Arduino since LED on PIN 13 is turned on. So the problem maybe just on your sketch.

To FIX analogWrite on PIN 9 try to set the PIN as OUTPUT with this statement:
pinMode(9, OUTPUT);

I cannot help you with lcd library that I don't know.

If you need for some help don't hesitate to write to me.


The bandgap voltage reference needs some time to stabilize, after you enable it. See http://jeelabs.org/2012/05/12/improved-vcc-measurement/

Doing 3 dummy measurements, gives it enough time to do that.


How to make two small micros communicate with my Arduino over BLE?

You can use SoftwareSerial to communicate with two modules from an uno. But You will have to wire 'em up separately, not through your shield. (making the total number of bluetooth modules 4.

You could also use your existing sheild and poll between the two remotes. I.e. disconnecting from one and connecting to the other at a regular interval.

For the micros and bluetooth for your button, you could use a HM10 with an ATtiny like in this instructable. He uses two HM10 modules to talk to each other. HM-10 is a popular BLE module. If you want regular bluetooth(2.0), you can use HC-05.


Can't store temperature in variable ( for further processing)

This line:

int temp1 = ((float)DHT11.temperature, DEC);

casts DHT11.temperature to an float, throws away the value, then assigns DEC to temp1. That is not what you want.

int temp1 = DHT11.temperature;


The Arduino core macro F() takes a string literal and forces the compiler to put it in program memory. This reduces the amount of SRAM needed as the string is not copied to a data memory buffer. Special functions are required to access the data stored in program memory. The Arduino core hides a lot of the typical usages such as:

Serial.println(F("Hello world"));

Further details of the low level access program memory access may be found in the AVR GCC libc documentation. The F() macro is defined as:

class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper*>(PSTR(string_literal)))

The FlashStringHelper class is used to help the compiler recognize this type of string literal when passed to Arduino functions. Below are some examples:

// String constructor with program memory string literal
String::String(const __FlashStringHelper *str);

// Print (Serial, etc) of program memory string literal
size_t Print::print(const __FlashStringHelper *);
size_t Print::println(const __FlashStringHelper *);

You should not use the Arduino core F() macro with anything other than a string literal.


Feed values to an array using keypad interfaced with Arduino Uno

customKeypad.getKey(); doesn't wait for the key press. it returns 0 if no key is pressed.

you should rewrite the sketch to a version where the loop() can loop and key presses are read as they are pressed.


Using Arduino wireless SD Shield to save data to sd card and send to PC over wireless network

"Arduino Wireless SD shield" is not "Arduino WiFi shield".

The code you have is for the Arduino WiFi shield. But you have Arduino Wireless SD shield for a XBee module. XBee is not WiFi. Zigbee protocol is different protocol then WiFi.

You can save data to SD card with the SD library. Install the library in Library Manager and try the examples.

Arduino WiFi shield:

Note: the Arduino WiFi library is only for this shield and clones


Fail to retrieve the value from gsm sim 900A by using AT Command to PHP script

I am not sure but, in this tutorial at page 8, it does almost the same code pattern like yours. You might want to check it. Sorry but I don't know PHP, I can't help you with it.

But I am confused with AT+HTTPACTION, since AT+HTTPACTION=0 is the read and AT+HTTPACTION=1 is the post. Check the tutorial and optimize your commands.

Also check this one. It writes WAIT=6 after AT+HTTPREAD before terminating it.


If you are using the MPU6050 library from jrowberg/i2cdevlib, the library does not have any kind of error handling, so it is unfortunately not easy to guess what went wrong, or even if something went wrong. If the getMotion6 function fails, it will simply copy corrupt data into your return values and it is not possible after the invocation to tell if the function succeeded and you got a valid reading, or if the function failed and you only got garbage back.

One possible problem is that the MPU6050 can be configured to use one of two I²C addresses (0x68 or 0x69) and you are using the default address, as implemented in the MPU6050 library (0x68). It might be worth to try the other address, in case your module is configured that way:

MPU6050 accelgyro(0x69);


FTDI to HM-10(CC2541) serial command no response

Ahhh...After few hours of struggling finally found the solution. The "HM-10" module I was using was a copycat module and "Both NL &CR" option should be chosen as a newline/carriage return character will be feed at end of the AT command. I found the solution from these two awesome articles:

Working with cheap bluetooth BTLE4 devices HM-10 BLE-CC41A

Comparing the HM10 and BLE CC41a Bluetooth

Hope this will be helpful for someone meet this problem in the future.


Okay, here is how it works, and I checked it to make sure.

Sure you can use hard paths, but every programmer hates using hard paths. They are not portable at all, and they lock your program in place. You use soft or hard links to the files in the project (look up the man pages on "ln"). But,... talk about ugly! So the question is how to do it "correctly"? The key is learning with what parameters and in what path the C/C++ compiler runs.

You will find the conclusion is NOT intuitive at all. Cutting to the chase: relative paths don't work correctly. Now, why?

But first, let me explain why anyone would want to place program files outside the project directory. Programmers like writing program classes, structs, methods, functions, macros, etc., once. As soon as the programmer solidifies the program fragment, he/she wants to put the files in a common tree and move on. Every program thereafter could use that private library. Also, by having the files in a central place, you won't have multiple copies and versions of each. One private library for many private programs.

As of 1.6.13 (Teensy does not yet support 1.8.*), relative includes start from the library, not your directory. It appears that the ano-to-C filter (remember that Arduino does a "conversion" to the target then calls the C/C++ compiler) starts where you installed your Arduino tree. In my case, I installed in "~/bin/arduino". Teensy's home is "./hardware/teensy". The entire home path for the libraries is "~/bin/arduino/hardware/teensy/avr/libraries" where you will find all the support program trees.

In a source file, the '#include "test.hpp"' statement correctly picks the file from your current directory. HOWEVER, if you use '#include "../test.hpp",' the include path does not start in your project directory. Instead it starts in "./libraries"! So the resulting path is:

#include "../test.hpp" ==> ./arduino/hardware/teensy/avr/libraries/test.hpp

In conclusion there is no clean way of making your own tree of tools in  a nearby directory. The only course is to commit your work in the Arduino library and be aware of those rules as well.


From your code you are using Timer0 in FastPWM mode with top = 0xFF.

In this mode, as used in your code, OCR0A defines the pulse width rate (more precisely, OCR0A / 256).

Timer0 uses port OC0A and OC0B to ouput PWM signals, in your code, you are using only OC0A (which is perfectly fine).

Now if you take a look at ATmega 328 data sheet, chapter 14.3.3 you will see that pin OC0A maps to port D, pin PD6 (on Arduino UNO, this is port D6, according to http://arduino.cc/en/Hacking/PinMapping168).

So this means that you have used the wrong port in your setup (Arduino pin D9 maps to OC1A, which is pin PB1 of port B on ATmega328, OC1A is used by Timer1, not Timer0).

Hence you should do the following to fix the problem:

Plug the LED to Arduino pin D6 instead of D9
Fix initialize_PWM() by replacing DDRB|=(1<<PB1); with DDRD|=(1<<PD6);

Otherwise, if you want to keep Arduino pin D9, then you will have to change the timer you use: Timer1 instead of Timer0. Updating the code is left as an exercise!


This could be an SD card SPI bus issue.

Note that because the W5100 and SD card share the SPI bus, only one can be active at a time. If you are
using both peripherals in your program, this should be taken care of by the corresponding libraries. If
you're not using one of the peripherals in your program, however, you'll need to explicitly deselect it. To do
this with the SD card, set pin 4 as an output and write a high to it. For the W5100, set digital pin 10 as a
high output.

  Check the Arduino shield datasheet.

Changing pin mode:

pinMode(4, OUTPUT);
digitalWrite(4, HIGH);


Wifi server to control led on and off from local webpage.. - ..if statement doesnt work...

Pretty sure your problem is coming from the fact that you chose to use the backslash as your terminator character. The backslash requires special handling when encoded as a URL. You can observe this by Googling for "\" and and the results page you'll see your query in the address bar assigned to the "q" variable:
q=%5C
my entire URL looked like this, you may have something a bit different:
https://www.google.com/?gws_rd=ssl#q=%5C

Ok - so if you want a quick fix, stop using the \ to terminate your commands, since backslashes are often used to help sort out special characters (like "TAB" as \t) it's a a really bad choice, but an honest mistake.

If you change your code to generate links terminated with dashes you can get around the issue

client.println("ON

");
client.println("OFF

");

and of course change your readStringUntil invocation too

client.readStringUntil('-');

Edit:
You might want to use the "" if the hostname part of your URL contains a space:
http://my-web-server.com/on

And one more alternative, seek the "%" instead since that's going to be used to encode the backslash. In that case you just need to change the readStringUntil()


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

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

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

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

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

Cheers!


Best practice to declare a 'static' text and save memory

The "traditional" way is to use PROGMEM and use const char * strings.

I don't use the "traditional" way. Instead I use some "helper" classes and macros that WString.h provides.

This does mean, though, due to limitations in C++, that you have to create your string constants in two stages.

First is to define your variables:

const __FlashStringHelper *stringOne;
const __FlashStringHelper *stringTwo;

Then you need to assign the actual strings to those variables within a function. This could be in setup(), but I prefer to define an initializeStrings() function that setup() calls:

void initializeStrings() {
    stringOne = F("This is the first string")
    stringTwo = F("This is the second string");
}

void setup() {
    initializeStrings();
}

You can then pass these objects (they're not really objects, it's all just some magic casting done by the compiler) as parameters to other functions using const __FlashStringHelper * as the type.  They can also be passed directly to any of the .print() and .println() functions provided by the Print class (which all Stream objects ultimately inherit).

If you want to use the standard C string library functions _P variants for manipulating the strings (concatenating them to other strings, for instance), you can simply cast them to PGM_P:

char temp[50];
strcpy_P(temp, (PGM_P)stringOne);
strcat_P(temp, (PGM_P)stringTwo);

Another alternative to all that is to use precompiler macros.

#define STRING_ONE F("This is the first string");
#define STRING_TWO F("This is the second string");

Again, you can cast those to PGM_P to use the _P variants of the standard C string library functions, and pass them directly to print functions, since they are replaced verbatim as F("This is the first string"), and F() does a reinterpret-cast to const __FlashStringHelper *.


How can I read servo motor readings via serial communication?

I'm assuming, that you are sending the angle value as a 1-byte value, so no ASCII encoded numbers. This is how the code in your question works, so it should be right.

You don't have to convert anything here. The Serial.read() function already returns an integer value and you are saving it to an integer variable. But in your code you only care for 2 different states (100 and 101), instead of the actual angle value. Now you only have to replace your if-statements and write this value directly to the servo:

Servo1.write(recValue);

EDIT:

You doesn't seem as you know how serial communication (to be exactly USART) functions. So I will explain further:

The data, that is send over serial is just a stream of bytes. All content, that get transmitted are converted to a stream of bytes. Every byte has a numerical value. For example a byte with the bit-content 00100000 has a numerical value of 32. But at some point in history it was necessary to send text with a byte stream. So someone invented ASCII, which assigns a character or control command to every numerical value from 0 to 127. So if you send a byte with the numerical value of 32, you could mean the actual numerical value 32, or you could mean the ASCII equivalent to 32, which is the space character. This is just an interpretation of the byte data, that flows through the serial interface.

So you have to investigate, in which kind you are encoding the angle value. If you use fwrite() in your Matlab code, you are most likely sending the byte value, which you can simply use as described above. If you use fprintf(), you are sending the angle value as an ASCII encoded string. The value 32 from above would then occupy 2 bytes with the characters 3 and 2, which correspond to the byte values of 51 and 50. In this case you should add a delimiter character at the end in fprintf() (for example the newline character "\n") and use Serial.parseInt() to get the angle value from the string.

You can read more of this in many tutorials about Serial communication that you can find in the internet. Also refer to the example, that come with the Arduino IDE.


The drive capacity of the Motor Shield should match the motors – two of the motors. The shield was probably designed for a load of one motor, and you're giving two, so it is possible that neither of the motors on that side is getting enough current to get started. Here are somethings to check to get started:

Find the drive capacity of the Motor Shield and compare it to the motors (if you don't have specs for the motors you could measure the current they draw if you have an DMM). It might be wise to measure the current anyway, just in case you have a defective motor or shield.
If the capacity or the current draw is out of line, that's your problem. You can probably just add a power transistor to the circuit to drive the motors in this case.
Try it with just one motor on each output and see if they run normally. If they do, that would suggest a loading problem or a defective motor or shield. You can sort out which is which by swapping sides – if one motor runs and the other doesn't, swap them. If the problem follows the motor, then blame the motor, otherwise blame the shield.


Are there any ePaper modules that are bigger than 2.7 inches for arduino

I would suggest you to start the other way: find a sw stack that is known to work and check if any of the controllers/displays it already supports fits your needs. This is how I would do it.

Here is a starting point.


Programing AVR 32u4 via ISP with other ISP device connected

Yes, that is possible and I've done the exact same thing with an ATmega328 which controls a DAC via SPI. If it wasn't possible ISP wouldn't be an option whenever SPI is already in use.
You should make sure that the NRF's CS pin is high while flashing the firmware, otherwise it might corrupt a checksum verification or memory readout.

Note the difference between ISP (in-system programming) and SPI (serial peripheral interface). Even though ISP uses SPI and they have similar abreviations they are not the same.


Can I place bootloader directly onto Atmega2560 and have USB?

I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

That is a misunderstanding.

The bootloader is on the 2560.  The 16U2 contains its own custom firmware which acts as a USB CDC/ACM interface to connect the USB to the 2560 as a TTL UART connection.

The same can be done using any number of other similar devices, such as the FT232R etc.

You cannot directly connect the USB to the 2560 since the 2560 has no concept of what USB is.  The 16U2 has that knowledge, but doesn't have as many IO pins as the 2560, so combining the two gives you a total system that both understands USB and has lots of IO.


How do I control a conveyor to start and stop in same location using optical rotary encoder

Although your solution would work, it seems open to problems such as missed clicks, starting at a different place etc.
A better, more robust and error free solution might be to use a hall sensor.
Essentially what a hall sensor does is close a switch when a megnetic force is applied. So all you have to do is add a magnet to your conveyor/chain. This way, you can easily control where you want it to stop just by moving the magnet, and it doesn't matter what the starting position is because it will always stop as soon as the megnet reaches the sensor.


float pwmDelta=((255/100)*(highLim-lowLim))/(tLim);

That line should be:

float pwmDelta=((255.0/100)*(highLim-lowLim))/(tLim);

Adding the .0 tells the compiler to do that math using floats and you get 2.55.  Without it the math is done with int and the result is 1 which isn't what you want.

analogWrite(motor1, 53.55);

Just write 54.  analogWrite only accepts integer values.

analogWrite(motor1, motorPWM=165.75);

You should really do that as two lines, an assgnment and then an analogWrite.  This way leads to confusing code.  Also, analogWrite only accepts integer values so your decimals are useless there as well.


Cited comment:

  Check pin modes. Should be INPUT_PULLUP and OUTPUT. Also, consider
  debouncing. – Mikael Patel

Please, try:

const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
//Should be INPUT_PULLUP and OUTPUT
    pinMode(rpin[i],OUTPUT);
    pinMode(cpin[i],INPUT_PULLUP);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
   delay(200);              // Also, consider debouncing.
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}


please tell me how do I fix this code down here(please tell in my easy English)

Variable names MUST NOT start with a digit. Only '_' and a-z are allowed!

1cd really should be lcd with an 'ell' instead of a one (1).


How to run multiple functions one after another?

I did not quite understand what you are actually trying to accomplish.
Neither you question nor your code is very clear in this respect. And
your code is probably buggy anyway, since it does not do what you
expect.

Then, I am just guessing: you may just want to fade a red LED up and
down, then a green LED up and down, and repeat the whole cycle
indefinitely. I am guessing right?

First of all, I would recommend you stick with the functions provided by
the Arduino core library, as they will make your life easier. The kind
of low level AVR programming you are attempting here is for advanced
users. You should learn the basics first before moving to that realm.

Here is how I would write that using the plain analogRead() function:

const uint8_t RED   = 6;  // pin connected to the red LED
const uint8_t GREEN = 5;  // pin connected to the green LED

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

// Fade an analog pin up and down.
void fade(uint8_t pin)
{
    for (int i = 1; i <= 255; i++) {
        analogWrite(pin, i);
        delay(10);
    }
    for (int i = 254; i >= 0; i--) {
        analogWrite(pin, i);
        delay(10);
    }
}

void loop()
{
    Serial.println(F("Fading RED."));
    fade(RED);
    Serial.println(F("Fading GREEN."));
    fade(GREEN);
}

Each LED fading up and down takes roughly 5 seconds:
2 ramps × 255 steps/ramp × 10 ms/step.


GPS: Not receiving any valid output from ATGM336H

while(GPS.available() > 0) {....

Also is the GPS unit outside?


What does the term "9g" in servo's rating mean?

According to Flite Test web site, the 9g reference is the weight without the wire lead. They measured one model at 8 grams rounded down. I suspect the weight also ignores the horn as well as the wire.

The article referenced on the web site calls the weight reference as a standard, which means that it more likely allows for heavier or lighter servos as long as the size of the servo matches.

If you purchase a servo for a model known to use a 9g servo, you know the hole you have to build for it to fit. If you purchase a 5g servo, it will be a different hole and you may have a 6 or 7 gram weight, but the servo fits as it should.


The event gets fired when a single character is received, not the whole string. You have to build the string up until you get to \r\n and then process it. This is my code for a similar project. It uses a protocol where > signifies the start of a message and \r signifies the end. processMessage is a function to process the entire message and update GUI elements etc. It is invoked using runLater because the serialEvent function will be on a different thread to the GUI thread.

StringBuilder message = new StringBuilder();
Boolean receivingMessage = false;
public void serialEvent(SerialPortEvent event) {
    if(event.isRXCHAR() && event.getEventValue() > 0){
        try {
            byte buffer[] = serialPort.readBytes();
            for (byte b: buffer) {
                if (b == '>') {
                    receivingMessage = true;
                    message.setLength(0);
                }
                else if (receivingMessage == true) {
                    if (b == '\r') {
                        receivingMessage = false;
                        String toProcess = message.toString();
                        Platform.runLater(new Runnable() {
                            @Override public void run() {
                                processMessage(toProcess);
                           }
                        });
                    }
                    else {
                        message.append((char)b);
                    }
                }
            }
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
            System.out.println("serialEvent");
        }
    }
}

A simpler version for you might be the following. processMessage is called whenever a \r or \n is received and there are some bytes in the message.

StringBuilder message = new StringBuilder();
public void serialEvent(SerialPortEvent event) {
    if(event.isRXCHAR() && event.getEventValue() > 0){
        try {
            byte buffer[] = serialPort.readBytes();
            for (byte b: buffer) {
                    if ( (b == '\r' || b == '\n') && message.length() > 0) {
                        String toProcess = message.toString();
                        Platform.runLater(new Runnable() {
                            @Override public void run() {
                                processMessage(toProcess);
                           }
                        });
                        message.setLength(0);
                    }
                    else {
                        message.append((char)b);
                    }
            }
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
            System.out.println("serialEvent");
        }
    }
}

Edit:

Two things fixed:  1. Using StringBuilder instead of String to save making a lot objects every time the message is incremented. 2. Make a copy of the message string before passing to runLater otherwise when it does run it will use the up to date version of the string, which could have new characters, and thus cause problems.

Edt 2:
On Windows I found it needed if(event.isRXCHAR() && event.getEventValue() > 0) as the event would sometimes be fired with 0 bytes causing a null point exception in for (byte b: buffer)


How much low analog voltage can Arduino uno read?

The Arduino Uno uses a processor containing a 10 bit ADC.  This means the ADC can resolve (if we do not consider noise) 2 to the 10th or 1024 voltage levels between zero and the voltage supplied to the Arduino Uno at the AREF pin.  There is a good explanation of the AREF pin in this stackexchange.com question / answer.  It is common practice to supply the AREF with voltages lower than the positive rail the processor is operating at to improve resolution of expected lower voltages.  For example, if you do not expect to measure voltages higher than 3.3 volts on a 5 volt Arduino, use the 3.3 volt supply as a reference.  Relative to using a 5 volt reference, using a 3.3 volt reference decreases your granularity from 0.00489 to 0.00322 volts per step.

Of course there is a lot of noise in most ADC circuits.  Finding the average of many ADC readings helps mitigate this problem.  Consider using exponential averaging.


Nick Gammon "Camera shutter speed timer"

Can you tell me what is happening [...]?

Not really, but here is a wild guess: your input signal is bouncy, the
ISR fires too often, your loop cannot keep up with the rate, and you end
up accessing endTime in the ISR and loop simultaneously.

If you have a scope, look at your encoder signal. Is it clean?

  would it be better to use a counter instead of interrupts?

Using the input capture feature of a timer will give you the best
possible accuracy, as you will have single-cycle resolution. In
contrast, micros() has only 4 µs resolution (64 times worse) and
the ISR may be delayed by up to ≈ 16 µs by the TIMER0_OVF
ISR.

You can use the FreqPeriod library you linked to as an inspiration for
writing your own timer-based code, but it will require some changes:

As pointed out by Nick Gammon in a comment, you don't need the analog
comparator, nor the conditioning RC network, as the encoder's outputs
are already digital. Or you may use a low-pass filter if the encoder
is bouncy.
You will use the input capture pins of either timer 4 (digital pin 49)
or timer 5 (digital pin 48). The other input capture pins are not
available on the Mega's pin headers.
You will replace ISR(ANALOG_COMP_vect) by either ISR(TIMER4_CAPT)
or ISR(TIMER5_CAPT) (the relevant “capture event” ISR). No need to
adjust a comparator threshold in the ISR.
In the begin() method, you will leave the analog comparator alone,
and you will enable the capture event interrupt.

Obviously you will have to study the
datasheet
before start coding.


The problem is here:

//Check if any pin from Port A has been pressed
if (PINA & 0xff){

Since the pullups are enabled, the default state of the pins is high. To detect a "press", they have to be pulled to ground. This changes the test to:

//Check if any pin from Port A has been pressed
if (~PINA) {

And for individual pins:

//Check if PA3 has been pressed
if (!(PINA & _BV(PA3))) {


How to post image using Arduino HTTPClient

Below is the perfectly working code I got from here.
#include <Arduino.h>
#include <WiFi.h>
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "esp_camera.h"

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

String serverName = "192.168.1.XXX";   // REPLACE WITH YOUR Raspberry Pi IP ADDRESS
//String serverName = "example.com";   // OR REPLACE WITH YOUR DOMAIN NAME

String serverPath = "/upload.php";     // The default serverPath should be upload.php

const int serverPort = 80;

WiFiClient client;

// CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27

#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

const int timerInterval = 30000;    // time between each HTTP POST image
unsigned long previousMillis = 0;   // last time image was sent

void setup() {
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("ESP32-CAM IP Address: ");
  Serial.println(WiFi.localIP());

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;

  // init with high specs to pre-allocate larger buffers
  if(psramFound()){
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 10;  //0-63 lower number means higher quality
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_CIF;
    config.jpeg_quality = 12;  //0-63 lower number means higher quality
    config.fb_count = 1;
  }

  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    delay(1000);
    ESP.restart();
  }

  sendPhoto();
}

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= timerInterval) {
    sendPhoto();
    previousMillis = currentMillis;
  }
}

String sendPhoto() {
  String getAll;
  String getBody;

  camera_fb_t * fb = NULL;
  fb = esp_camera_fb_get();
  if(!fb) {
    Serial.println("Camera capture failed");
    delay(1000);
    ESP.restart();
  }

  Serial.println("Connecting to server: " + serverName);

  if (client.connect(serverName.c_str(), serverPort)) {
    Serial.println("Connection successful!");
    String head = "--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"imageFile\"; filename=\"esp32-cam.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n";
    String tail = "\r\n--RandomNerdTutorials--\r\n";

    uint16_t imageLen = fb->len;
    uint16_t extraLen = head.length() + tail.length();
    uint16_t totalLen = imageLen + extraLen;

    client.println("POST " + serverPath + " HTTP/1.1");
    client.println("Host: " + serverName);
    client.println("Content-Length: " + String(totalLen));
    client.println("Content-Type: multipart/form-data; boundary=RandomNerdTutorials");
    client.println();
    client.print(head);

    uint8_t *fbBuf = fb->buf;
    size_t fbLen = fb->len;
    for (size_t n=0; n<fbLen; n=n+1024) {
      if (n+1024 < fbLen) {
        client.write(fbBuf, 1024);
        fbBuf += 1024;
      }
      else if (fbLen%1024>0) {
        size_t remainder = fbLen%1024;
        client.write(fbBuf, remainder);
      }
    }
    client.print(tail);

    esp_camera_fb_return(fb);

    int timoutTimer = 10000;
    long startTimer = millis();
    boolean state = false;

    while ((startTimer + timoutTimer) > millis()) {
      Serial.print(".");
      delay(100);
      while (client.available()) {
        char c = client.read();
        if (c == '\n') {
          if (getAll.length()==0) { state=true; }
          getAll = "";
        }
        else if (c != '\r') { getAll += String(c); }
        if (state==true) { getBody += String(c); }
        startTimer = millis();
      }
      if (getBody.length()>0) { break; }
    }
    Serial.println();
    client.stop();
    Serial.println(getBody);
  }
  else {
    getBody = "Connection to " + serverName +  " failed.";
    Serial.println(getBody);
  }
  return getBody;
}


Does HC-05 module buffers the data received?

I didn't find any help in any data-sheets I could find, either. So I'd suggest a simple experiment, sending increasingly large packets before the other side attempts to read anything, until some data goes missing. The packets don't even need to be very sophisticated if all you want to know is whether N_received == N_sent and for what maximum 'N'.
Update:

All bytes were received correctly if there is no delay but with
increasing delay in reading from HC-05 data was not fully received and
with delay greater than 800ms only 63Bytes were received.

If you're collecting data as it arrives, then you can't measure the buffering. When you wait until all data has been set before you try to read any, the number of bytes you receive is the buffer size. It sounds like a 63 byte buffer, probably only what the HC-05's hardware UART can buffer, without using any of its memory to increase that.


What is the correct folder structure for including local headers in my Arduino project?

The reason why you can't reference the parent folder of your sketch when compiling is because the Arduino IDE doesn't compile your sketch in that folder. Instead it writes out the files from the IDE itself into temporary files in a "build" folder and compiles them in there - so the parent folder then does not contain your header file because the IDE has no clue about that.

So you need to put your header file somewhere that the IDE does know about - and the simplest place is where the libraries are.

A library is nothing more than a header file in a folder (both named the same) with optional source and other header files.  If you place your header in a folder in your libraries folder the IDE will see it as a library and you can include it into any sketch.

So you would have:

Documents/
    Arduino/
        libraries/
            MyHeader/
                MyHeader.h
    MyFancyProject/
        NodeOne/
            NodeOne.ino
        NodeTwo/
            NodeTwo.ino
        NodeThree/
            NodeThree.ino


Wire.endTransmission() is where the action is. Nothing is actually sent until that point. Wire.beginTransmission just gets ready for sending and Wire.write (if used) adds stuff to an internal buffer.

If it hangs at that point you probably have dodgy hardware. Check the connections are correct (ie. SDA/SCL the right way around, and that it is powered, and that you have a common ground).

Then try a pull-up resistor between SDA and +5V, and SCL and +5V. A typical value resistor (for both resistors) would be 4.7k.

I see from the linked page that the board already has 10k resistors. Hopefully you did not cut the jumper links. Whether or not you did you might want to augment them with 4.7k resistors. Also keep the cable runs short.


Arduino doesnt seem to be reading my pin states

Thanks all of you,

Indeed there is nothing wrong with my code. The problem is indeed in the pull-down resistors, I rebuild the connection on a breadboard and works perfectly. I will have to check my PCB that contains all relays and resistors, the problem has to be on that board, bad connection or something like that.

However I would like to state that on the Osoyoo Uno board, the whole thing worked perfectly, so there has to be something different between Osoyoo Uno board and another Arduino board.

Here is the schematic to my PCB board. I checked it again, but i think all the digital pins have actually pull-down resistors active.


Well, the answer of the question "Can it replace Arduino" - yes, in many cases it can.
Whether it would be "the Arduino killer" - I doubt it.
There are multiple arduinos and ESPs in my home and 1 ESP in my office running 24/7 as a part of my self-made (and constantly under development) smart home solution, together with 1-2 PCs. On top of that I have several experiments / unfinished projects involving the ESP.
So, from my not-so-limited experience, here are the pros and cons of ESP compared to Arduino:

++++ Internet connectivity built in!
++ Faster clock and more memory.
+ Runs on 3V3 (most, but not all Arduinos are 5V) so it can interface 3v3 devices (like most of the display modules) directly, without level shifters.
+ The "basic" ESP-12E costs about as much as an Arduino nano or pro micro.

- The "basic" ESP-12E is 2.0mm pitch, not 2.54mm, making it a pain in the ass to work with.
- There are breakouts that make it easier for prototyping, but they increase the cost and take too much space on a breadboard / protoboard.
- The most common breakout - NodeMCU - is more expensive and has pins remapped, major annoyance, unless you program it in Lua, which is only ok for very simple projects. IMO, it should be used for prototyping only.
- They run on 3v3, making it hard to interface 5V modules, fully turn on most MOSFETs, etc.
- They are extremely picky on their power supply.
- They draw significantly more power than the Arduino when not transmitting and much more when transmitting.
- They are almost always worse for battery operated projects - you need 3v3 regulator (which has quiescent current), you need to sleep a lot (and you need GPIO16 broken out for that) and at the end of the day an arduino + a low-power radio will do the same job while lasting significantly longer on battery.
- They have less GPIO pins and some of them must have set voltages at startup (GPIO0 - high, GPIO2 - high or floating, GPIO15 - low), also they "wiggle" some of their IO pins on startup, often making them unusable for many devices.
- They only have one ADC, and to my knowledge it is slower than the already slow Arduino ADCs, plus you can only use it with 0-1.1V (internal reference).
- Many of the Arduino libraries work out of the box or are already ported, but many don't. You either have to port them yourself or wait for someone to do it. In general, the Arduino community is much bigger and more mature, so most "noob-friendly" tutorials, libraries, etc. are provided for the Arduino.

Having that said, the ESP8266 is still great and extremely useful. Even Lua is useful for quick small projects. In most cases where internet connectivity is required, they seem to be the best solution. In many other cases, whether you will use ESP or Arduino actually doesn't matter. And sometimes the Arduino (or the little ATTiny85) is the better choice.
As always, "the right tool for the job" is the way to go.
Or combination of tools.


ATtiny85 MIDI IN with less than 3V -can it be done?

The H11L1's minimum supply voltage is 3 V.
There are low-power optocouplers like the TLP2361, but event those do not go below 2.7 V. (And those limits are actually designed for 3.3 V ± 10 % or 3.0 V ± 10 %.)

To get a high-speed optocoupler for lower voltages, you have to build it yourself from discrete parts, e.g.:

(R1 is sized for the PC817-A's minimum CTR of 50 %; higher CTRs should use a lower value for R1. Q1 can be any random small-signal transistor. Adjust R2 for about 1 mA, depending on VCC.)


Can LilyPad Main Board interface with a sensor via UART?

Yes you can.

Lilypad <> Other device using UART

Rx         <    Tx

Tx         >    Rx

Note that you cannot use 5V with the lilypad if you do this. If you do want to use 5V with the Arduino, then you'll have to put a voltage divider between the Tx and Rx (other wise you might fry the other UART device using 3.3V.

Also, when you upload the code FROM your computer TO your Lilypad, you have to connect all other UART device connected to the Lilypad. Connecting other devices to the Tx and Rx of the Lilypad while uploading a code to it might cause lag or bugs.

Hope I anwsered your question!


Current Sensor ACS712 not changing its value even when connected bulb is lit

In a comment about rZero = 511;, you wrote:

For illustrative purposes only - should be measured to calibrate
sensor.

This may well be the cause of your problem. If, instead of 511, the
“zero” of your measurement is around 445, then you end up measuring a
non-existing DC current of about 3.23 A. When you turn on the light
bulb, you add roughly 435 mA (100 W / 230 V) of AC
current. The total RMS current you see is then:
√(3.232 + 0.4352) ≈ 3.26 A
Barely visible at the resolution at which you are printing the result.
And this is assuming you are using a 100 W bulb, as shown in the
diagram. These bulbs are getting hard to come by. If you are using
anything less powerful, you may not see any change in the displayed
value.
As a quick and dirty fix, you may replace 511 by 445. A better
solution would be to compute the quadratic average of the AC part of the
signal alone. In other words, compute:
√(average(current2) − average(current)2)


HTTP post request in JSON Format using SIM900 module

Hi all use this code below for establishing HTTP connection with the server. And to neglect the 601 or 504 error use proper posting format. Here I'm using JSON format. I just gave manual data. Ignore those errors in HTTPINIT, AT+SAPBR=2,1. The data will be posted to the server

 #include<SoftwareSerial.h>

SoftwareSerial client(2,3);

String reading="{  \" : 1,  \"latitude\" : 12.983027,  \"longitude\" : 80.2594,  \"timestamp\" : 100,  }";

void setup()
{
  Serial.begin(9600);
  client.begin(9600);
  delay(500);

  if(client.available())
  {
    Serial.print("Connected");
  }
  else
  {
    Serial.print("NotConnected");
  }

  //initSIM();
  connectGPRS();
  connectHTTP();
}

void loop()
{

}

void connectGPRS()
{
  client.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=3,1,\"APN\",\"www\"");//APN
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=1,1");
  delay(1000);
  ShowSerialData();

  client.println("AT+SAPBR=2,1");
  delay(1000);
  ShowSerialData();
}

void connectHTTP()
{
  client.println("AT+HTTPINIT");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CID\",1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"URL\",\"http://xxx.xxx.xx/Listener/\"");//Public server IP address
  client.println("AT+HTTPPARA=\"URL\",\"http://testServer/Listener/\"");//Public server address
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
  delay(1000);
  ShowSerialData();

  client.println(reading);
  delay(1000);
  ShowSerialData;

  client.println("AT+HTTPACTION=1");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPREAD");
  delay(1000);
  ShowSerialData();

  client.println("AT+HTTPTERM");
  delay(1000);
  ShowSerialData;
}

void ShowSerialData()
{
  while(client.available()!=0)
  {
  Serial.write(client.read());
  delay(100);
  }
}


Can an Arduino Micro receive commands from another microcontroller when hardwired together?

You cannot do this with the micro USB ports.  You will need to use I/O pins.  Either serial or I2C would be good options.  It might be advisable to use I2C if you want to control multiple 'slave' microcontrollers as they can all sit on the same bus.  Using the serial port would require multiple transmit and receive pins on the master controller, likely requiring software serial ports (high overhead).  Also, if you don't use the serial port for comms, then you can use it for debugging.


Use a PIR Sensor to detect the movements of a paper

If the paper is hot when it comes out of the printer, possibly.  Could be unreliable though.

Better would be to place a photo-interrupter (or IR LED and IR Photodiode) in the path of the paper to detect a break in an infra-red beam.


LED Matrix Display with dissimilar brightness

There's two options:

Use a matrix driver that supports different brightnesses per pixel, or:
Rapidly display a different arrangement of pixels in quick succession. The pixels that are on more often are brighter.

Option 1 basically does option 2 in hardware.

The theory is simple:  For one LED you can vary the brightness by using PWM - that switches the LED on and off very rapidly. The longer it is on the brighter it appears.

You can do the same with a matrix of pixels. Instead of dealing with one pixel though you are dealing with, in effect, a series of "images". Each "image" has a different combination of pixels. The more "images" you have the greater variation you can get in your pixel brightnesses.

For example if you first display a frame of:

. . . . . . . .
. . # # # # . .
. # . . . . # .
. # . . . . # .
. # . . . . # .
. # . . . . # .
. . # # # # . .
. . . . . . . .

followed by the image:

. . . . . . . #
. . # # # # # .
. # . . . # # .
. # . . # . # .
. # . # . . # .
. # # . . . # .
. # # # # # . .
# . . . . . . .

then you will get a bright circle(ish) shape with a dimmer slash through it.

The only problem with this method is flicker. You have to have your matrix refreshing very fast. The more "images" you have to display in sequence the more it will flicker and the faster you will have to refresh your matrix to compensate.


Averaging input from multiple input over a fixed amount of time (estimated)

This function will average readings on an analog pin, include it and use it in place of analogRead(...) and it should do what you want.

int aveAnalogRead(int pin, int ave=10, int delayms = 0)
{
    int tot = 0;
    for(int i=0; i<ave; i++)
    {
        tot += analogRead(pin);
        if(delayms) delay(delayms);
    }
    return tot/ave;
}

in your loop():

for (int analogPin = 0; analogPin < 6; analogPin++)
{
   int sensor = aveAnalogRead(analogPin);
     <<do your work here>>
}


9V batteries are not meant for high-current discharge, as you would find when powering a motor. Not only that, they are low capacity. If you need to power motors, you should use batteries such as C or D cells in series to build the voltage required, or try Lithium-Polymer (LiPo) for a rechargeable option.

On a side note, the L293 H-Bridge is a poor choice of H-Bridge these days, especially for a battery-powered project, as there are more efficient motor driver ICs these days.


No. The Arduino (or not the "normal" Arduinos) doesn't have enough memory to decompress JPEG.

I made a JPEG decompressor for chipKIT boards the other day, and it uses the absolute bare minimum memory possible, and still comes it at close to 128kB. Far more than any "normal" Arduino board.

You can possibly do it with one of these new-fangled Linux-based Intel boards that are being sold as Arduino these days, but they are not your normal run-of-the-mill Microcontroller but closer to a Raspberry Pi.

Speaking of which, the Raspberry Pi is probably a much better choice than any Arduino board for the kind of thing you are trying to do.


Unable to compile SimpleTimer code - Exit status 1

There are quite a few Arduino libraries called “SimpleTimer”. According
to arduinolibraries.info, the one you get through the
library manager is Alexander Kiryanenko's SimpleTimer. The
one described in Arduino Playground is Marcello Romani's
version. You should try the examples that come with the
specific library you install.


Is it possible that function will get a parameter that can be int OR char?

In C++ you can create a template function. (The ArduinoJson [] operator is a template too.)

#include <ArduinoJson.h>

StaticJsonDocument<512> tempJDOC;

template <typename T>
void setValue(const char *key, T value){
  tempJDOC[key] = value;
}

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

  setValue("a", 5);
  setValue("b", "xyz");

  serializeJson(tempJDOC, Serial);
}

void loop() {
}

the compiler will create function based on this template for every different type you use as second parameter in your sketch


I would recommend the nRF24L01.

You don't need one pipe per node - just one pipe.

Each pipe is effectively an address that a node responds to - having multiple pipes means you can have multiple addresses on one node (like aliases) - but of course you only need one address per node, and hence one pipe per node.

The range is more than adequate (with the antenna version I have managed to get hundreds of meters no problem) and the price is so low as to be negligible.


Arduino keypad matrix example? ( teensyduino )

By your description, you don't have a matrix.  You have them wired as just 8 straight switches.

A matrix would be if you had the 4 switch pins of one keypad wired to the same switch pins of the other keypad, and the two common connections from the keypads wired to two separate IO pins.

At the moment your code is responding whenever a button is in the low state. Instead it needs to respond only when the button transitions from the high state to the low state.  To do that you need to know what state all the buttons were in the previous pass through loop to compare them to what they are in this pass through loop - and if any have changed then they have either been pressed or released.

You should also implement debouncing to that you don't get false presses.

If you don't want to learn how to do all that yourself I have a handy library that will do it all for you:

https://github.com/MajenkoLibraries/DebouncedInput

If you want to convert your setup to an actual matrix to save on IO pins you want to read the Arduino Keypad tutorial:

http://playground.arduino.cc/Main/KeypadTutorial


SoftwareSerial constructor is rx pin first then tx pin.

You have SoftwareSerial soft(2,3); But you said that

D3 - TX
D2 - RX

Which means soft rx is going to its rx and soft tx is going to its tx. These need to be swapped. Either swap the wires or change it to:

SoftwareSerial soft(3,2);


Difference in increment & decrement loop execution speed

Comment out these 2 lines

Serial.print("the value is=");
Serial.print("\t");

And report back on the speed difference.
Why not add a reading of micros() before and after each loop and see how much difference there really is?  All time variables are unsigned long.

startTime = micros();
// your loop
endTime =  micros();
duration = endTime - startTime;
Serial.println (" "); // line break
Serial.print ("duration in uS = ");
Serial.println (duration);

I edited to add some missing )s and a 2nd line break.


Need help: Cast from 'char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]

You can't just cast a string to a numeric type - C just doesn't work that way. What you're actually casting is the address in memory that the string resides at.
Instead you need to take the content of the string and interpret it.
For instance, you might take each pair of characters and combine them into a HEX value in a string that you then interpret as a number. That could be done a number of ways.
For example:
char temp[3]; // Temporary space for the conversion string
// Copy two characters into the temporary string
temp[0] = payload[0];
temp[1] = payload[1];
// and terminate the string properly
temp[2] = 0;
// Convert the string using base 16
uint8_t val = strtol(temp, NULL, 16);

In your example string you have 16 characters, which would be 8 bytes of data. So you could put it in a loop:
char temp[3]; // Temporary space for the conversion string
uint8_t vals[8]; // Array to store your values

// Iterate over the values
for (int i = 0; i < 8; i++) {
    // Copy two characters into the temporary string
    temp[0] = payload[i * 2];
    temp[1] = payload[i * 2 + 1];
    // and terminate the string properly
    temp[2] = 0;
    // Convert the string using base 16
    vals[i] = strtol(temp, NULL, 16);
}

Of course there are "lighter" ways of doing it that don't involve an intermediate string or the strtol() function.  For example I often use this little function:
uint8_t h2d(char hex) {
    if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
    return(hex & 0xf);
}

That takes a single character and converts it from hex to decimal. So you can combine that with bit shifting and OR to create a byte from two characters:
val = h2d(payload[0]) << 4 | h2d(payload[1]);

In your loop that would look like:
for (int i = 0; i < 8; i++) {
    // Convert the string using base 16
    vals[i] = h2d(payload[i * 2]) << 4 | h2d(payload[i * 2 + 1]);
}


Program an ATMega328P and use it without Arduino board

You can remove an ATMEGA from an Arduino and use it in your own board, however when used on a typical Arduino board the chip will be fused for an external crystal as a clock source, rather than the (simpler but less accurate) internal clock.

You cannot change the clock source over ISP unless the clock source the chip is currently expecting is operational, so if you want to change the clock selection you will want to do that before removing the chip from the Arduino.

However, you can also provide a clock crystal and its two capacitors (or a substitute resonator which often has this built in) on your external board.

Typically chips (even those pre-flashed with a bootloader as a convenience) are cheaper than boards, so it's unclear why you would want to move the same chip off the Arduino as opposed to using another.  You will want a USB-logical level serial adapter anyway, and once you have that you can do development on the bare chip on your board, even if you do initial testing on the Arduino.  In a pinch if you don't have the USB converter you can either pull the chip out of an Arduino board and run wires from its D1 and D0, or hold the on-board chip in reset to allow you to borrow those serial lines without interference.


You should:

Contact Elegoo and ask them if there is any support/return possible.
Consider buying an official Arduino, to support Arduino.
Consider even cheaper options.

Software wise, any "Arduino compatible" board will work with the Arduino IDE, if not, you should return it (if possible).

Some boards may have cheaper hardware and cause issues with:

Serial drivers (some use a cheaper chip, but this often can be fixed)
Input voltage or power stability
Durability (including min/max temperature)

So you should consider if support or the possibility to return a product is more important than paying a little more.


Connected a 330nF capacitor between one pin of the PT100 to -DC, and one 330nF between -DC and ground.


Your charger may be able to handle 300mA, but you're pulling that power through your Arduino and that isn't good.  The pump should have a separate power supply, or at least be powered in parallel with the Arduino.  Don't pull power for a motor from the Vin pin unless you just want to destroy the Arduino.


Wrong characters received with Bluetooth Mate Gold using Software Serial

Maybe you fixed your issue, but I'm writing to help other people.

void loop()
{
  if (bluetooth.available())
  {
    dataFromBt = bluetooth.read();
    Serial.print("Receiving:");
    Serial.println((char)dataFromBt);


SIM800L and Arduino Sleep - getting whimsy Serial output after 5 calls

Give AltSoftSerial a try, it's hands down superior.

Reset might work but it does not actually solve your problem, it just swipes it under the mattress. Also, have you considered ditching that String? It is the source of many problems regarding memory. You could relatively easily substitute it for an array of chars instead. Something like this, taken from example#2:

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}


In the specification sheet linked to in the post we find this:

  -30+/-10nA/ppm

This is a very small amount of current.  The Arduino ADC is a voltage sensing device and (unless modified) has a range of 0 to the operating voltage of the Arduino.  Usually 3.3V or 5V.

Converting nano Amps to that range of voltage will require additional hardware.  A stock Arduino and code are unlikely to make use of such a sensor.

The conversion of such small amounts of current to voltages measurable by a stock Arduino is not trivial. And most answers do not fit into the short format of stack exchange.  Here is an Engineering Design News article on the subject.


You can use the DS1307 itself just fine, but you are probably using a breakout board. These boards have (pull-up) resistors on it that will pull-up the I2C lines to 5v, while you only want 3.3v. This will not damage the arduino, but could damage chips like the  TSL2561, that can only handle 3.3v.

On the board you indicated you are using, you need to remove R2 and R3

Other 5v sensor breakout might also have pull-ups to 5v. Easiest way to check, is to connect 5v and ground, and then measure the voltage on the SDA and SCL pins. If it's 5v, then it has pull-up resistors that need to be removed.


How can I deal with rapid fluctuation of Anemometer readings?

A:  Use a running average

In the initialization I include an array to hold 10 values

// Wind Speed Anemometer
const int sensorPin = A3;
int sensorValue = 0;
float sensorVoltage = 0;
float windSpeed = 0;
float voltageConversionConstant = 0.004887586;  // (5/1024)
float voltageMin = .33;   // 0.4 in the documentation
float windSpeedMin = 0;
float voltageMax = 1.5;   // 2.0 in the documentation
float windSpeedMax = 32;

float ws[10] = { };      // (initializes all to zero)
int wsIndex = 0;
float wsTot = 0.0;
float wsDisplay = 0.0;

Then in the Loop I fill the array with values and display the average of the 10 readings stored there

  // Wind Speed
  sensorValue = analogRead(sensorPin);
  sensorVoltage = sensorValue * voltageConversionConstant;
  if (sensorVoltage <= voltageMin) windSpeed = 0;
  else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);

  if (wsIndex<9) {
    ws[wsIndex] = windSpeed;
    wsIndex++;
    }
  else {
    wsTot = 0.0;
    for (int i=0;i<=9;i++) wsTot = wsTot + ws[i];
    wsDisplay = wsTot / 10.0;
    lcd.setCursor(0,3);
    lcd.print(wsDisplay);
    lcd.print(" MPH  ");
    wsIndex = 0;
    ws[wsIndex] = windSpeed;
    }


There are two areas of non-volatile storage in an Arduino: Flash and EEPROM.

Flash is where your program and constant values are stored. Variables with default values also have their default values stored in Flash.

EEPROM is a much smaller area with no real fixed purpose - you can store whatever values you want in there.

Flash can only be written to by code that is in the bootloader area of flash. This is important. A program cannot modify itself. Only the bootloader can modify a program - and then only in chunks ("pages"). It has to erase a whole page before it can write data to it.

The reason why you can't modify Flash from your main program is simple: Flash is the only place code can be executed from. If you erase the page of flash that contains the code that is programming the Flash then everything dies. Horribly. So it's stopped in its tracks by not allowing it to happen in the first place.

EEPROM, conversely, can be written to by anything - the bootloader or the main program. And on top of that individual values can be modified at will - no need to erase pages.1

So to answer the question behind your question ("How can I store and modify settings?"): it's quite simple - store them in EEPROM.

The IDE has examples of how to use the bundled EEPROM library, and there are more details in the Arduino reference manual.

1: Some systems don't have EEPROM, so they emulate it using Flash. These systems still have to erase the Flash in pages, but they try to do it transparently. Some (such as the ESP8266) use a commit() method to update a batch of values. Others, such as chipKIT boards, use wear levelling and separately indexed writing to reduce the need to erase pages.


How to use a grove speaker without using delayMicroseconds?

It's just a small amplifier and speaker - what you put into the SIG pin gets amplified and sent out the speaker.

Instead of doing the audio generation manually like that I would suggest using the tone() function which will generate an audio tone at a desired frequency in the background.

https://www.arduino.cc/en/Reference/Tone


How to transfer data from arduino to android via bluetooth?

Is it possible to transfer the data from arduino to android via bluetooth?

Yes.  The HC-05 just creates a serial connection over bluetooth.  You can treat it just like any other serial connection, such as the USB connection between the Arduino and your computer.

What data you send and in what format you send it is entirely up to you.


Motor shield and Arduino Led not turning on when connected to laptop and Arduino is heating up

0

You might have burned one of the onboard voltage regulators. In my case, it was AMS1117 which was burned and my Arduino was behaving similarly. You will notice that the Arduino will work with an external power supply connected to the Vin pin of Arduino and it will not become hot.

 In short, the small chip which is getting hot is a voltage regulator may be AMS1117 and you have to replace it manually or buy a new Arduino


What is preventing my code from checking the number of pushbutton values for a correct/wrong answer?

Let us start with the simplest issue in your code:

Timer = millis();
...
if (Timer >= 2000UL) {
...
}

After 2000 ms this is always true (for about 49 days)?

Cheers!

Please format your code if you expect anybody to take the time to read it and help.


Without looking at the library, you can check yourself if this method (INA3221SetConfig) is called from the begin method (of the same class). Just trace back the methods manually until you find a call to this method.
About the | or 'bit-wise-or' operator (see https://en.wikipedia.org/wiki/Bitwise_operations_in_C), these are used to set bits in a byte/word/long.
Most registers have 8, 16 or 32 bits and with the | operator you can easily set multiple bits at the same time. Each value (e.g. INA3221_CONFIG_ENABLE_CHAN) has a value that is a power of 2 (mostly defined in the form 1 << ..something.. you can add them (with +) or | them together, but | is more clear what the purpose is and repeatedly calling | the same bit twice is not a problem (it still gives the same result).


Is it possible to make an Arduino send signals to an RC receiver?

The easiest way would be to open up the transmitter, desolder the potentiometer used for the stick and solder the cables to Arduino's PWM instead. Then use analogWrite() to simulate stick position. If your TX would use that potentiometer with more than 5 V, you'll not able to use full ppm values. A RC or a RCL filter may be needed between PWM output and RC input to "smooth" the PWM into an analog signal. There are a lot of online calculator to find good R, C and L to polish your signal.

This assuming your TX is using potentiometer like stick; if it is a really cheap one, it may be using buttons. If this is the case, then you connect a transistor in parallel with the button, that way you can keep manual button.

Another way is to program your Arduino to look for ppm signal (normally 50 Hz with high starting value with a period from 500 to 2000 µs) and then look for this signal into the Tx PCB; if found cut the trace of the generator and solder your cable from Arduino. I've seen around a lot of libraries outputting ppm (they are used on drones to mix single ppm channel back to PPM to use only one pin from logic board without having to hack standard RX


Here's a sample program you could use as reference, just replace the values in the array and adjust VALUES_NUMBER accordingly.

Disclaimer: I didn't try to compile/run it, but it should give you an idea of how to use the values you already have.

// These are Arduino Pins that support "analog" output.
const unsigned short ANALOG_RED_PIN = 3;
const unsigned short ANALOG_GREEN_PIN = 5;
const unsigned short ANALOG_BLUE_PIN = 6;

const unsigned int VALUES_NUMBER = 12;

const unsigned short REDS[VALUES_NUMBER] = {
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05,
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B
};

const unsigned short GREENS[VALUES_NUMBER] = {
  0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05
};

const unsigned short BLUES[VALUES_NUMBER] = {
  0x09, 0x0A, 0x0B, 0x03, 0x04, 0x05,
  0x00, 0x01, 0x02, 0x06, 0x07, 0x08
};

void setup() {
  pinMode(analogRed, OUTPUT);
  pinMode(analogGreen, OUTPUT);
  pinMode(analogBlue, OUTPUT);
}

void loop() {
  unsigned int counter;
  for (counter = 0; counter < VALUES_NUMBER; counter++) {
    analogWrite(ANALOG_RED_PIN, REDS[counter]);
    analogWrite(ANALOG_GREEN_PIN, GREENS[counter]);
    analogWrite(ANALOG_BLUE_PIN, BLUES[counter]);
    delay(1000); //sleep 1 second
  }
}


Your Timing is working, you can test it with the Serial monitor. So your problem is at some other place. Using delay() is from my perspective not a good solution, you did it better the way you already made.

For testing your sketch I included the communication for the Serial Montior (I had to comment out the LED activation since this is working in a different way on my board, and I also made the intervalls Shorter to see better the effect within the test sketch). Here you find the necessary changes and the output of the Serial Monitor.

My recommendation is to look with a simple Sketch if you are able to switch on/off your LEDs sperately without Timing to come closer to your problem. I dont think it is the Timing/use of millis().

#include <M5Stack.h> // needed for my board

// each "event" (LED) gets their own tracking variable
unsigned long previousMillisLED12 = 0;
unsigned long previousMillisLED13 = 0;

unsigned long previousMillisLED3 = 0;

// different intervals for each LED
int intervalLED12 = 50;
int intervalLED13 = 500;

int intervalLED3 = 2000;

// each LED gets a state varaible
boolean LED13state = false;     // the LED will turn ON in the first iteration of loop()
boolean LED12state = false;     // need to seed the light to be OFF

void setup() {
  Serial.begin(9600);
  //  pinMode(13, OUTPUT);
  //  pinMode(12, OUTPUT);
  //  pinMode(3, OUTPUT);
}
void loop() {
  // get current time stamp
  // only need one for both if-statements
  unsigned long currentMillis = millis();

  // time to toggle LED on Pin 12?
  if ((unsigned long)(currentMillis - previousMillisLED12) >= intervalLED12) {
    LED12state = !LED12state;
    // digitalWrite(12, LED12state);
    // save current time to pin 12's previousMillis
    previousMillisLED12 = currentMillis;
  }

  // time to toggle LED on Pin 13?
  if ((unsigned long)(currentMillis - previousMillisLED13) >= intervalLED13) {
    LED13state = !LED13state;
    // digitalWrite(13, LED13state);
    // save current time to pin 13's previousMillis
    previousMillisLED13 = currentMillis;
  }
  Serial.print("LED12: ");
  Serial.print(LED12state);
  Serial.print("  LED13: ");
  Serial.println(LED13state);

}


Hardware damage from executing tight polling loop over extended periods of time?

There's nothing to save except battery charge (if your system even uses a battery). It will take just as much energy to delay() as it would to keep polling. The only way to save energy is to put the processor to sleep instead of delaying. And polling will be so brief that you might as well keep the sleep time short, too.

You probably don't need 10 uSec poll intervals; I should think your mouse would be plenty responsive with 1 mSec intervals. If polling takes, say, 100 uSec (and that's a total guess) and you sleep the processor for the other 900 uSec, you'll cut the energy use by 90%. If you don't need to save energy, it won't matter whether, or how long, you delay.

Update:

  "Does it make any difference at all, in terms of wear & tear or stress
  placed on the CPU, how many loops I choose to make in one second? I'm
  considering something in the range 0.1Hz -> 100kHz Assuming that I
  keep heat under control and other vital parameters within their
  nominal operating levels, is it true that the frequency I choose won't
  make a bit of difference, one way or another?"

Yes, it is true. Your CPU can run full speed continuously, safely. It won't overheat from continuous running. Only if some part of your project is trying to draw too much current through the CPU; then that will cause heating, but the CPU polling a bunch of inputs is well within its specs.


I recommend reading ArduinoSleepCode. Where it demonstrates placing the avr into a sleep state and using an interrupt to awake from the sleep state. In your case you can connect the output of your IR demodulator to the interrupt  pin, to simular awake.

Ken Shirriff's IR library allows you to use any pin as a receive input, so that you can use INT0 or 1 on D2 or D3. If you need to use a different pin, the Microtheron's github fork uses Pin Change interrupts. (I am not sure if stock sleep.h will awake from PCint, like int0 or 1 will, without tweek. Section 10.1 of data sheet says it will.)


to return 'epoch' seconds there is a function time in time.h

time_t now;
time(&now);

time_t is defined as long

this time is retrieved by the ESP32 SDK from NTP servers configured with  ESP32 Arduino function configTime

EDIT: it is the standard C time() function


How to wire and control a 16mm button with 2 legs using arduino?

A pushbutton is a pushbutton. It is a momentary switch. Since it has flexible wires, and needs a place to mount, you should probably wire it using a breadboard.
That pushbutton looks like a panel mount pushbutton. You might want to mount it in a pice of plastic or sheet metal. (Unscrew that nut up by the red part that you press. Measure the outside diameter of the threaded part. Drill a hole ≈1/64" (≈0.4MM) bigger than the switch diameter into the plastic/metal. Insert the pushbutton from underneath the panel. screw the nut back on to secure it. Tighten moderately tight with needle-nose pliers, being careful not to round off the corners of the nut.
To wire it:
Get a breadboard. Run wires from your Arduino to the breadboard.
Wire the pushbutton into the breadboard as well.
There are various libraries that offer switch debouncing, or you can write your own fairly easily.
I suggest using INPUT_PULLUP mode, and wiring your switch between an Arduino digital input and ground. When the switch is open, the input will read HIGH. When you press the the switch, the input will drop to LOW.
If you want to debounce the switch input yourself: When the switch changes state, note the value of millis(), and ignore any new changes for a brief period (try 20-100 mS).


The USB to serial and LEDs are done with the ATmega16U2 (the chip near the USB socket).

If you look closely you'll see there are 4 pad near the chip, JP2 in the schematic. You could solder some wire to it to connect your leds. You could then slightly modify the firmware running on the ATMega16u2, and upload it using DFU.

I did this on my arduino uno to break out the reset signal, so I could use my UNO to program an separate ATMega328 over serial.

In your case you could use the pads connected to PB4 and PB5 (as the original code uses PD4 and PD5), so the you only have to change DDRD and PORTD, to DDRB and PORTB in LED.h.


MKR WIFI 1010 Providing 3.3V to breadboard

In short: VCC = 3.3V

The Arduino MKR WiFi 1010 board documentation is not complete. Well, at least they have the warning that the processor is running at 3.3V and the voltage levels of the pins should never be above 3.3V.

The page of the Arduino MKR ZERO has more information in the "documentation" tab. The VIN pin is the 5V power input, the 5V pin is unregulated 5V output (when the board is powered by USB or the VIN pin) and VCC is the regulated 3.3V output.

The term "VCC" means that it is the voltage at which the processor is running. Since it is a 3.3V Arduino board, it is the 3.3V voltage pin. That 3.3V should be used to power sensors. The "Tech Specs" tab at the MKR ZERO tells that it can supply up to 600 mA. That is the same for the MKR WiFi 1010, because the same AP2112K-3.3 voltage regulator is used.


How can I attach sensors without a shield for a wearable project?

The accelerometer may be pretty easy (since it may not need to be in close contact with the person), but the GSR and skin temperature will need to be touching the person to work.

The first thing you will want to do is to identify the sensors that you want to use, and then come up with some ideas for how to make them wearable so that you can measure the parameters that you're looking for. Will you be able to attach them with straps, or does the attachment need to be more subtle or more comfortable? Small breakout boards are handy, but they may make the sensor uncomfortable to wear.

I'd suggest taking at look at the Adafruit site for some ideas on wearables and sensor interfacing. There is a lot of useful information there and much of it focuses on Arduino based designs. For the most part the sensors they sell and use are well documented either with data sheets or code (or both).


ESP 01 - reset settings to default values

Current ESP-01 firmware versions do not have an AT+IPR command. If you're trying to change the ESP's baud rate to use it with SoftwareSerial, the command to do so (in recent versions of the firmware) is: AT+UART=9600,8,1,0,0 for 9600 baud, 1 stop bit, no parity, no flow control.

The full syntax is: AT+UART=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>, where <databits> is the number of data bits per frame, 5,6,7,or 8; <stopbits> is 1, 2, or 3 for 1, 1.5, or 2 stopbits (respectively); <parity> is 0, 1, or 2 for None, Odd, Even (respectively); and <flow control> is 0, 1, 2, or 3 for None, RTS, CTS, RTS and CTS (respectively). Most serial communication and devices that most of us will ever see will be 8 data bits, no parity, and 1 stop bit, abbreviated as "8N1". Flow control is sometimes used, but often it is contained in the data stream itself, such as sending Ctl-S and Ctl-Q from the keyboard to manually stop and resume incoming data transmission.


Why we have to put our functions before void loop and void setup into VScode+platformio?

Because that is how C works. The Arduino IDE hides it from you by adding function prototypes at the start of your code.

  I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

const byte menuColor = 0XF206;

That can never work. The value 0x06 will be assigned to menuColor since a byte is only 8 bits.  You need to learn to use data types that are suitable for the values you are trying to store in them.


Clearly the compiler does not know what tmElements_t means.

It is defined in TimeLib.h

In your program you reference Time.h instead, where it is not defined.

So:  Change

include <Time.h>

to

include <TimeLib.h>

and it should clear that error.


How to send data from an Arduino to PC, without using the Serial Monitor?

I believe you are looking for something like the Telemetry library.

Full disclaismer : I am the author

It allows you to send string, numbers, arrays, sparse arrays through the serial port for instance. Each sent data has a label, called topic, that is used to identify it.

The Pytelemety command line interface then allows you to connect to the serial port, plot received data in real time, write parameters to reconfigure the arduino from the computer, etc.

Example of arduino code thats send an incrementing counter

#include <Telemetry.h>

Telemetry TM;
int8_t counter;

void setup() {
  TM.begin(115200);
  counter = 0;
}

void loop() {
  TM.pub_i8("count",counter);
  counter++;
  delay(10);
}

Overview of the CLI (Command-Line Interface)

Overview of a graph (not produced by the arduino program above)

Output to file is not implemented yet, although all received data is logged to a file (but this log also contains system information). However, this is an interesting feature, quite straightforward to implement, that I might add in coming days if you are interested.

Central documentation is available here.


DFRobot GSM / GPS shield with UNO init error

The dfrobot board has a weird boot button system that you need to follow to boot up the board. I spent ages attempting to get it to work before I finally achieved anything.
There is a blue led on the board that will flash continuously at different rates if the chip has been correctly powered and is searching for a mobile network.
I noticed that you commented it the while(!sim808.init()) line. This attempts to power the board on automatically, but I do remember something being funny about the implementation.
From doing a while load of research the dfrobot breakout board is not the best hardware implementation of this chip. Actually from memory there aren't any modules I have been able to find which satisfy all my requirements for a project. I'd recommend looking at all the documentation dfrobot provide on their website. Hopefully that should get you working.
Summary: it's an insanely fiddly process to get it working, but the boards are functional


Help! Interfacing LCD with Arduino using 8255A Intel peripherals

You will not be able to use 8255 pins as parameters to the the LiquidCrystal library without making substantial changes to either the library or the Arduino core.

The reason is that to configure or change a pin on the 8255, you will need to go through a series of operations manipulating the ATmega pins to which the 8255's microprocessor bus interface is connected.  You can learn about the necessary operations by reading the 8255 data sheet.  Also keep in mind that the 8255 does not have per-pin configuration - rather, the first two ports must each be either entirely inputs or entirely outputs, while there third port can be split in half.

Once you know how to set a pin, you will need to have the liquid crystal functionality trigger these operations.

One approach would be to create a heavily modified version of the library which knows how to work through the 8255.

Another would be to create a modified version of the Arduino core which has additional pin numbers corresponding to the 8255's pins, and generates code which does the necessary intermediate bus operations to access them.  However this will be quite challenging - you have to make sure the intermediate code gets in there in all paths, and figure out how it will handle cases where code tries to set pins that must have the same mode to conflicting modes.

As others have said, you would practically be better off using a different MCU with more I/Os - either an Arduino Mega, or one of the ARM-based boards.


Can RX and TX be temporarily transposed on demand?

On an AVR-based Arduino, you can selectively enable the transmitter and
receiver side of the UART (c.f. the datasheet of your MCU). Thus, you
could in principle just connect all the TX and RX together, and make
sure only one transmitter is enabled at a time, while all the others are
in high impedance. If you do this, I would strongly recommend you put a
current-limiting resistor in series with each TX, just in case.

For example, on an Arduino Uno
(Atmega328P),
you can use the following functions:

static inline void enable_tx()  { UCSR0B |=  _BV(TXEN0); }
static inline void disable_tx() { UCSR0B &= ~_BV(TXEN0); }
static inline void enable_rx()  { UCSR0B |=  _BV(RXEN0); }
static inline void disable_rx() { UCSR0B &= ~_BV(RXEN0); }

Edit: Beware that Serial.begin() enables both the transmitter and
the receiver.


Arduino 1.6.4 not showing any /tty/ options in Serial ports

I had the same problem when updated to 1.6.4, but with a Spark fun Pro micro.
Did a "reset to bootloader" on the pro micro, and hit upload, and it worked
 out nice and it still does!


How to read info from an Xbee Pro S2B to an Arduino with a Xbee Pro S2B

You have two serial connections. One for the main USB of the board and one for the XBee.

So you need to read from the XBee and write to the serial USB?

I don't know what speed you have configured for your XBee so I have set it to 9600.

This example reads from the XBee and writes to the Serial/USB port

#include <SoftwareSerial.h>

SoftwareSerial xbee (2,3);

int myData = 0;
int ledPin = 13;

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

    pinMode(ledPin, OUTPUT);
}

void loop()
{
    if (xbee.available())
    {

         int myData = xbee.read();

         Serial.print("Data has arrived on the Arduino");
         Serial.write(myData);
         Serial.println();

         if(myData == '1')
         {
             digitalWrite(ledPin,HIGH);
             Serial.write(myData);
         }
         if(myData == '2')
         {
             digitalWrite(ledPin,LOW);
             Serial.write(myData);
         }
     }
 }

Note: Your example also used Serial.write() with the wrong argument DEC which applies to Serial.print(). X-CTU and Arduino both send ascii which is also what the Serial.print() does. However the Serial.read() just reads the byte so we need to use Serial.write() to send the same bytes back to the other end.

You can also make life a bit easier by replacing xbee.available() with Serial.available(). Then use the Arduino IDE serial monitor to both send and receive. This means that you just use the one USB connection to prove the code.


Best way of storing extra data for Arduino project

EEPROM writes are limited to about 100k cycles.  They are for permanent or semi-permanent data (like your absolute speed threshhold - 120kmh, for example).

You should not store your speed camera base here.

Get a MicroSD adapter and save your data there.  Looping thru 36000 speed trap locations is going to put a toll on your processor and memory.  I recommend that you determine a binding box (+/- 2 degrees, for example) and save a temp file with only those traps inside the box.  recheck every time your position changes a full degree (N/S or E/W).

Notice: in some countries, Brazil for example, distributing information regarding speed trap locations is illegal (obstruction of justice).


Using Arduino microcontrollers without board

I have a post about a breadboard Arduino - in that I demonstrate the minimal amount of parts you need to use the controller (which is not much).

Example of wiring it up:

If you want to use an external crystal or resonator you can add that to the board like this:

8 MHz crystal shown, but you could use 16 MHz. Or change the fuses and use the internal oscillator.

Schematic showing how you could (if you wanted) add an ICSP header and an FTDI header:


two dimensional array with 3 characters per entry?


Sending large structs via nrf24l01 leads to cliping of some structs members

Your payload is too big. You will have to split it to smaller pieces.

NOTE: If you'd use a library like RF24Mesh then you'd not have to worry about it.


Do you need an ESC to run this brushless DC motor with Arduino Uno?

No. It has an ESC built in.

You just provide power and a PWM signal, and optionally a direction signal.

To test:

Connect red to +12V.
Connect black to 12V GND and to Arduino GND
Connect white to D5
analogWrite(5, 128);