The IO drivers of most common logic chips or microprocessors such as the ATmega on your Arduino are nowhere near strong enough to drive typical electromagnetic motors.

To drive a motor, you should use a higher current switching device - a standard solution for bidirectional control being an H bridge part such as a TB6612FNG, L293D, L298, etc.

These are commonly sold on "motor shields" which you can plug into your Arduino, if you want to experiment with the concept before building something (and if you do want to build something, reviewing such a working schematic first would be a good idea).

You can in theory put an L293D or its DIP-packaged work-alikes on your breadboard, but you will need some care to get it right, especially if you use one of the other parts which requires external catch diodes.

Finally, you should not be powering most motors from the Arduino's onboard regulator or a USB port, but rather should use an external power supply.

=============

Responding to your edit, by  changing connections to place the the motor between one pin and the 5v supply, you have done two things:

1) You have made it so that the voltage difference across the motor can be applied in one direction only, therefore it can only rotate in one direction.

2) You have made it so that only the N-channel MOSFET in an output driver is involved in powering the motor.  That change is almost a useful idea, as N-channel devices are in fact much more capable than P-channel devices of similar dimension (and practical capacitance, voltage rating, and other tradeoffs) due to the greater mobility of negative charger carriers.

But this is still not really a solution, as it is unlikely that your motor's current rating is within even the current sink rating of the N-channel side of the ATmega output.

If you want a simple, unidirectional motor control, you could pursue this idea using one external N-channel MOSFET (or even a biploar NPN power transistor, which will be less efficient but also less delicate) to connect the unpowered side of the motor to ground.

If you want bidirectional control, you will need either + and - power supplies, or four external switching devices taking the roles of the low current N-FET and P-FET totem poles inside each of the two on-chip IO pin drivers you started with.


There is nothing in the default megaAVR initialization that causes SCK to behave in this manner; it is all caused by the bootloader.

Fortunately all you have to do to solve this is disable the bootloader. Unprogramming the BOOTRST fuse (ext:0) will cause execution to start at address 0 instead of the beginning of the bootloader on reset.


Install Arduino IDE in Raspberry Pi 3 model B

Visit https://www.arduino.cc/en/Main/Software in your browser, and click the Linux ARM link under ‘Download the IDE’.

cd Downloads/
tar -xf arduino-1.8.3-linuxarm.tar.xz

Extract the file to your /opt directory, then open a Terminal and run the install.sh script to install.

sudo mv arduino-1.8.3 /opt
sudo /opt/arduino-1.8.3/install.sh

You will find Arduino IDE under Menu > Programming. Open the app to start programming your Arduino board.

Hope this helps.


Arduino UNO LED half brightness when connected to digital GND but not analog

Despite double checking my cables before asking this question, it seems I had connected the LED's cathode to digital pin 13, and not GND. The issue is now resolved. Takeaway: Triple check your cables :)


Efficient way to store array with repeating values?

Without a better understanding of what the data is or how you intend to use it it's impossible to give you real recommendations.

However it is simple enough to store your data in flash memory.

Since X is just a sequential value it can, as you have noted, be ignored.

For the rest, a simple array in flash which you then read with pgm_read_<X>() where <X> is the data size that you are using.

All this can be read on the Arduino PROGMEM Reference Page although the documentation is not great.

So here's a little example:

const int values[] PROGMEM = {
   100, 399, 2847, 1, -497, 32, 4370
};

void setup() {
    Serial.begin(115200);
    for (int i = 0; i < 7; i++) {
        Serial.println((int)pgm_read_word(&values[i]));
    }
}

void loop() {
}

The casting of the return from pgm_read_word as an int is needed to interpret the sign bit properly (it returns unsigned by default).


It depends on the application. For something like a rechargeable torch, Arduino might exceed the specifications. For a weapons system, NEVER (and this is one of the specific prohibitions in the license agreement - see section 1.5 note: link currently broken). You also have to consider that there's literally thousands of armies in the world and they all have different standards. What might be acceptable to one might not be acceptable to another. Hamas uses rockets I wouldn't consider safe for anything, and they use them effectively - the Qassam rocket would never meet US military standards but it works great for Hamas.

US military standards are so complicated, nobody can answer this question for you. You're gonna need an army of lawyers to do that... here's a link to some documents to get started though...

Please note there are multiple standards which may apply to a given device. For example, you will see common off the shelf desktop computers (running Windows) used for some things in a military installation, but they could never be used to control a vehicle. Bottom line - you're gonna need a lawyer to navigate this. (You are better off selling your devices directly to soldiers, if you can live with that if it fails.)

http://www.dsp.dla.mil/ - Terrible site - get used to that if you want to deal with govs.

OH BTW... if you want to use Arduino to prototype something, and you plan to remove "Arduino" later, running straight from the ATMega - that's the whole point of Arduino! It is a prototyping system, not intended to be used wholly in products. Arduino is very little more than a break-out board for the ATMega processor, a robust (kinda) power supply, and a runtime environment in C++.


Correction from another answer for number2:

number2 = (unsigned long)byte3 <<24 | (unsigned long)byte2 <<16 | byte1 <<8 | byte0; // = 4.000.000.001

And in the first round of loop number3 is correct, all others are wrong as number3 holds a result from previous loop.

  number3 = byte3; // all magic lays here
  number3 <<= 8;
  number3 |= byte2;
  number3 <<= 8;
  number3 |= byte1;
  number3 <<= 8;
  number3 |= byte0;


speckTxtKey[]= 0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00;

That's not how you assign an array.
And you never defined a type for the array.

It sould be:

byte speckTxtKey[] = {0x65, 0x74, 0x69, 0x4c, 0x19, 0x18, 0x11, 0x10, 0x09, 0x08, 0x01, 0x00};

EDIT:

I checked the source of the library to figure out how to use it, but it doesn't seem the library is meant for actual use.

SpeckTxtLen and SpeckKeyLen are macros inside SPECK_AVR.h, which are supposed to be changed there, not in your code.

The library also defines speckTxtKey inside SPECKenc_AVR.cpp with predefined test data based on the chosen length.

This library looks like a test implementation of the speck cipher, which was just dumped onto GitHub.


You need to get your head around the Finite State Machine (FSM).

It is a programming method which allows your program ("Machine") to be in any of a certain number ("Finite") of states ("State").  One state would be reading pressure. Another state would be "testing", or whatever.

I wrote a tutorial ages ago about it: http://hacking.majenko.co.uk/finite-state-machine


Hibernate Arduino for 12hrs with rtc1302 module

You need 3 pieces of code and one replacement:

1) Ditch ds1302 and get yourself an RTC with an interrupt pin (like DS3231 which Jot suggests). It will make your life easier.

2) Setup your RTC to fire an interrupt every 12 hours.

3) Since you have successfully implemented a sleep mode, try to wake your Arduino up using a hardware interrupt. See Nick Gammon's guide for interrupts, and read carefully about waking your micro with an external interrupt. You can prototype it using a pushbutton, which will either connect your interrupt pin to GND or Vcc. Use an appropriate resistor as well. This guide has good information for starters.

To sum up: you'll have your Arduino sleep at all times and your RTC set to fire a hardware interrupt. When fired, the interrupt wakes Arduino, and the interrupt code will handle your measurements.


Runtime Error when using array of structs of unknown size as variable within class - some kind of overflow issue?

The problem is most likely here:

_array = new MeasuredMass[_size];

You're allocating _size * sizeof(MeasuredMass) bytes in the heap. If _size is too big the amount of memory allocated becomes too great and it fails to allocate. You should check if _array is NULL or not after the new.  If it's NULL then it failed to allocate.

The problem is that heap allocation is limited to 2kB. This is regardless of the amount of memory you actually have in the chip. This is a limit imposed by the compiler (actually the libraries bundled with the compiler) and is set by a value in the linker script.  It's something I've been campaigning to have removed from the libraries for many years, but it's always fallen on deaf ears. So much so that I provide a "fixed" version of the compiler in UECIDE that removes this hard limit.

The best thing you can do is to not use dynamic allocation. Instead have a statically created array which you then pass to the constructor.

MeasuredMass massBuffer[25];
RingBuffer massRing(massBuffer, 25);

and:

RingBuffer(MeasuredMass *buf, unsigned int size){
  _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
  _array = buf;
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}


Should I use an accelerometer or gyroscope in my project?

An accelerometer is a better choice here. For your application, you aren't worried about initial motion but just acceleration. Plus, an accelerometer is cheaper.


How to connect dual brushless motors to arduino

It looks like you provide the correct voltage to the VCC and GND pins to power it, and connect the CW/CCW and PWM (and GND of course) to your Arduino - the first to control the direction, and the second to a PWM pin to control the speed.

You can use the FG pin to monitor the speed from the internal hall effect sensor if you want.


Issues with connecting to an Adafruit FLORA board

Seems like whatever code was running on the Flora was corrupted. As soon as I hit the reset button, the board would momentarily pop up in the Arduino IDE, and after doing this a few times, I managed to upload the "Blink" sketch while the board was visible to my system. After that the board started working normally. It reports its name as "Adafruit FLORA" under "get board info", and the serial monitor/onboard LED work just fine.


Point-to-point Communication of Arduinos with RFM LoRa Shield

The simplest way is to just cast the integer into an array of 2 bytes and send that.  Assuming int temperature:

rf95.send((uint8_t *)&temperature, 2);

To make it more portable you can use the size of an integer instead of 2:

rf95.send((uint8_t *)&temperature, sizeof(int));

Reading back, you just cast the buffer you have received as an integer, or combine the data manually (which may be safer since the buffer may be misaligned on a more powerful system than an 8 bit Arduino):

int temperature = buf[0] | (buf[1] << 8);

(Assuming it was sent from a little-endian 8-bit system).

If you want to send the number as plain text, so it can be easily read by a human, you want to print it to a string:

char temp[6];
sprintf(temp, "%d", temperature);
rf95.send((uint8_t *)temp, strlen(temp));


It would be easier if you used Arduino <--> Python compatible libraries to ensure the communication between the two is robust and reliable. An example of such libraries would be pySerialTransfer and SerialTransfer.h.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs.

Example Python Script:

import time
from pySerialTransfer import pySerialTransfer as txfer

if __name__ == '__main__':
    try:
        link = txfer.SerialTransfer('COM17')

        link.open()
        time.sleep(2) # allow some time for the Arduino to completely reset

        while True:
            send_size = 0

            ###################################################################
            # Send a list
            ###################################################################
            list_ = [1, 3]
            list_size = link.tx_obj(list_)
            send_size += list_size

            ###################################################################
            # Send a string
            ###################################################################
            str_ = 'hello'
            str_size = link.tx_obj(str_, send_size) - send_size
            send_size += str_size

            ###################################################################
            # Send a float
            ###################################################################
            float_ = 5.234
            float_size = link.tx_obj(float_, send_size) - send_size
            send_size += float_size

            ###################################################################
            # Transmit all the data to send in a single packet
            ###################################################################
            link.send(send_size)

            ###################################################################
            # Wait for a response and report any errors while receiving packets
            ###################################################################
            while not link.available():
                if link.status < 0:
                    if link.status == -1:
                        print('ERROR: CRC_ERROR')
                    elif link.status == -2:
                        print('ERROR: PAYLOAD_ERROR')
                    elif link.status == -3:
                        print('ERROR: STOP_BYTE_ERROR')

            ###################################################################
            # Parse response list
            ###################################################################
            rec_list_  = link.rx_obj(obj_type=type(list_),
                                     obj_byte_size=list_size,
                                     list_format='i')

            ###################################################################
            # Parse response string
            ###################################################################
            rec_str_   = link.rx_obj(obj_type=type(str_),
                                     obj_byte_size=str_size,
                                     start_pos=list_size)

            ###################################################################
            # Parse response float
            ###################################################################
            rec_float_ = link.rx_obj(obj_type=type(float_),
                                     obj_byte_size=float_size,
                                     start_pos=(list_size + str_size))

            ###################################################################
            # Display the received data
            ###################################################################
            print('SENT: {} {} {}'.format(list_, str_, float_))
            print('RCVD: {} {} {}'.format(rec_list_, rec_str_, rec_float_))
            print(' ')

    except KeyboardInterrupt:
        link.close()

    except:
        import traceback
        traceback.print_exc()

        link.close()

Example Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    // send all received data back to Python
    for(uint16_t i=0; i < myTransfer.bytesRead; i++)
      myTransfer.txBuff[i] = myTransfer.rxBuff[i];

    myTransfer.sendData(myTransfer.bytesRead);
  }
}

Note that you can send more than just individual chars with these libraries. It is possible to transfer floats, ints, bytes, arrays, and even structs (or any combination of the like) within your program using the libraries! See the examples in SerialTransfer.h for more info

For theory behind robust serial communication, check out the tutorials Serial Input Basics and Serial Input Advanced.


Your analysis is indeed correct, you can communicate between Arduino and ESP using the serial protocol.

Electrically speaking you must ensure the RX and TX pins are crossed:

Arduino RX goes into ESP TX
Arduino TX goes into ESP RX

Also, the two devices MUST have a common ground, the GND pins of the Arduino and the ESP8266 must be tied together.

You don't need level shifters because, even if the ESP8266 runs at 3.3V, its IO ports are 5V tolerant.

Also, as you already pointed out, the two devices must set the same speed (aka BAUD rate) in order to comprehend each other.

In case you decide to transmit binary data please also consider the two devices use a different architecture: Arduino is 8bit, ESP8266 is 32bit, meaning they have different word size (the minimum allocation unit size).

I had to face the word size issue when I first tried to exchange a struct between an Arduino and a RaspberryPI (also 32bit)...


It would probably help if you were using the right pin.  In the pins_arduino.h file for the Uno is this diagram:

//                  +-\/-+
//            PC6  1|    |28  PC5 (AI 5)
//      (D 0) PD0  2|    |27  PC4 (AI 4)
//      (D 1) PD1  3|    |26  PC3 (AI 3)
//      (D 2) PD2  4|    |25  PC2 (AI 2)
// PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
//      (D 4) PD4  6|    |23  PC0 (AI 0)
//            VCC  7|    |22  GND
//            GND  8|    |21  AREF
//            PB6  9|    |20  AVCC
//            PB7 10|    |19  PB5 (D 13)
// PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
// PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
//      (D 7) PD7 13|    |16  PB2 (D 10) PWM
//      (D 8) PB0 14|    |15  PB1 (D 9) PWM
//                  +----+

That shows that pin D 13 is PB5 which would be a binary value of 0b00100000 not 0b00001000 as you have, which would be PB3, or pin D11.

The only way I can come up with 0b00001000 is if I count from the left (wrong) and start at 1 (wrong) rather than count from the right (right) and start at 0 (right).


Can't burn bootloader through Arduino Nano clone ISP to atmega328p

Your slave micro isnt resetting when your master wants it to reset.

Ie: master sends a reset signal before initiating further communication, and it seems that your slave not being reset.

So its not responding.

Once cross check your isp signal lines.


Convert fuel level sender resistance ranges - good Arduino project?

The Toyota sensor may be using 12V instead of 5V, which would mean you'd need to use a voltage divider to get it down to the range that the Arduino analog inputs can read.
You will need to find a digital potentiometer that can handle the voltage range that the
GM controller wants to see.  This may be 0-12V, which would be a problem since the AD5206 is only good for 5V.
However, as dandavis implies with his RC filter comment, you may be able to simulate the full 0-12V range with PWM, where the Arduino pin drives a transistor to chop up the 12V, and an RC filter smooths the result for the GM control unit.  That's probably your best approach.
Alternatively, if the GM controller is only looking for a go/no-go level, you can use the
transistor to switch in a simple voltage divider to get the right voltage from 12V.
The sensors are (presumably) just variable resistors (2-terminal) not full 3-terminal potentioneters.  They will most likely be using a series resistor to make a voltage divider, and the control unit (or gage in the Toyota) will reading the resulting voltage. You will want to either find out the value of the series resistor or measure the voltage that the gage sees.  It might already be in the 0-5V range.  The GM control unit may have the series resistor built in (or be using a current source), in which case you should measure the voltage its sensor input sees when you give it the max and min resistance.  This will be good to know when you are trying to drive it with your own circuit,


AnalogWrite only working for one pin of RGB LED

You are trying to combine the use of the Servo library and PWM on pins 9 and 10. You can't do both. PWM on pins 9 and 10 uses the same timer as the servo library.

As it states on the Servo library web page:

  The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.


Direct answer
F() takes immutable string literals, that are known at compile time, and places them into flash ("PROGMEM") instead of RAM.  snprintf() creates strings at runtime and places them into a mutable array.  The two things are fundamentally incompatible.
Limited compile-time concatenation
A very limited form of what you're trying to do could probably done like this:
#define MY_STRINGIZE(x) #x

myMethod(F("There are " MY_STRINGIZE(60) " seconds in a minute"));

This expands to:
myMethod(F("There are " "60" " seconds in a minute"));

Adjacent string literals are concatenated together, which makes this:
myMethod(F("There are 60 seconds in a minute"));

All that said, you could just write 60 in there directly.  And there's none of snprintf's formatting capabilities possible here.
There is not a compile-time version of snprintf available in Arduino.  And I don't think the features of the C++ (or C) language are there to support the creation of one either.  Odds are there is a better way of achieving what you really want to do.
Working around this altogether
Often it's not necessary to concatenate strings at all, particularly if you're just to turn around and write them to a Stream, or more generally Print subclass, e.g. Serial, LCD, SDFile, SoftwareSerial, etc.  Concatenating things for you is a large part of what these do.  It is not necessarily to do it yourself in advance.
If you have a string literal and constant (or variable) and want to keep as much of it out of RAM as possible, using two separate .print()/.println() helps you do this:
printCapableThing.print(F("AT+CIPSTAT="));
printCapableThing.println(index);

F() places "AT+CIPSTAT=" into flash.
If index is a constant it will also wind not being resident in RAM.

Side note
I realize you're asking about, getting as much into flash as possible, but I also can't help but point out this same basic technique applies to this otherwise awful idea, for somewhat different reasons:
Serial.println(String(F("Key ")) + keyname + " : " + value);

This creates a horrific mess of allocations and deallocations and unnecessary copying, where if you just let the Stream/Print object do its job by calling print()/println() multiple times.  The result code is more reliable, smaller, and where not I/O-bound, faster when you do.


How to turn off or stop Access Point network in ESP8266?

I've already solved, by using a function of the library Wifi, specific for the connections in "Access Point" mode:

WiFi.softAPdisconnect (true);

Reference:
softapdisconnect


Ardutester Millenium I2c Lcd Not Showing Anything!

The schematic you posted is not for I2C. You have a connection to the regular 2x16 LCD character display. For the I2C an SSD1306.


Communication with Arduino and electronic device(for example tv or computer) through rs 232 cable

You have 2 problems:

You use the Serial.print() function, which outputs ASCII encoded characters. When sending "0" this way, actually the value 48 (or 30 in hex) will be send. RealTerm seems to display hexadecimal values, so you would get a long series of "30"'s. This is not really a big problem, you only shouldn't expect zeros to display there with this code. You can use the Serial.write() function to send direct byte values instead of ASCII codes.
You initiate the SoftwareSerial on the same pins, that are reserved for the Hardware Serial. This cannot work properly, because both libraries will try to use the same pins. Choose other pins for Rx and Tx of the SoftwareSerial interface.

EDIT:

Also you are setting pin modes for Rx and Tx of the SoftwareSerial. I don't know, if this can cause a problem, but at least you don't have to do this. The library will handle setting the pins correctly.

EDIT2: Further explanation about binary, hexadecimal and ASCII representation of the Serial byte stream

There are different methods to display a stream of byte data (like the stream from your Serial interface). Let's look at the decimal value (the one you are using when invoking arithmetic operations like +, -) 48. These are the different representation of this number in different numeral system (The first two characters mark the numeral system; 0b for binary, 0x for hexadecimal):

binary: 0b00110000
hexadecimal: 0x30

There are more numeral systems, but these are the most important ones. But the byte stream can also be used to look like a sequence of characters. For this the ASCII standard was born long time ago. In simple ASCII every value from 0 to 127 got assigned to a character or control action. The terminal program reads the byte stream and shows the corresponding characters according to the ASCII table. There are expansions to this model, to display more possible characters, but this is the very basic principle. With it, you are able to actually send human readable text from your Arduino to another device.

The Serial.print() function is made for this human readable text, so it will send an ASCII representation of the input parameter. The ASCII value of the character "0" is 48, which corresponds to a hexadecimal value of 30.

Now I'm not sure, if your terminal program shows hexadecimal or ASCII values. I though of the first, because all characters in your first image are digits or characters from A to F, which is the range of hexadecimal values. It didn't seem likely to not get other characters, when you have ASCII encoded text with random values in it. But I'm currently not sure, if the Serial.print() function would automatically print a hexadecimal representation in form of ASCII text, if given a hexadecimal value (I don't think so, but it might be possible). Please try to use the Serial.write() function and try sending different value while watching the output of RealTerm.

And please search for a settings, that determines, how the received byte stream is interpreted. This would make clear, what RealTerm is doing here. Also make sure you understand the relation between binary value and ASCII character. If this is still not clear enough, you can google for in detail explanations. There are tons of tutorials on that.


Can the Arduino Eclipse plugin use the libraries installed by the Arduino IDE?

I fear that what you want is not 100% possible.
For libraries I am 100% sure it will work but the problem is the platforms.
UPDATE arduino IDE (no longer)? decompresses libraries and as such the libraries are unusable in Sloeber.

Lets start with the Libraries
What you do is:
In arduino eclipse ide remove all libraries from the library manager.

In windows->preferences->arduino->"private libraries path" add the libraries folder in the arduino IDE install and add the libraries folder in the arduino15 folder maintained by the library manager.
It is important to point to the parent folder containing the libraries. All subfolders are assumed to be libraries.

Then the boards
The problem here is that the boardsmanager adds environment variables to link boards to tools. You may have read remarks about A.RUNTIME.TOOLS.AVR-GCC.PATH and A.RUNTIME.TOOLS.AVRDUDE.PATH not being defined. Well it is the boardsmanager that maintains these based on json file content.
If you can limit yourself to 1 version of AVR, SAM, AVRDUDE, BSON,... tool chain you can "make it work" as follows:
Step 1: Keep as little boards as possible installed. You have to keep at least 1 or the plugin will reinstall the AVR boards of Arduino when started.
Step 2: In windows->preferences->arduino->"private hardware path" add the hardware folder in the arduino IDE install and add the packages folder in the arduino15 folder maintained by the Arduino IDE boards manager.
Step 3: Recreate the project in eclipse as described in your other question.
Step 4: If the build fails modify the [eclipse installation]/arduinoPlugin/post and pre processing files to try to get it to work.
Step 5: in project properties->Arduino select apply and OK (this will take your changes in step 4 into account)
Step 6: Goto Step 4

Good luck
Jantje


ESP8266 using EEPROM to store a value of 100,000

The esp doesn't have an eeprom, but emulates it in its flash. Therefore 100.000 cylces will not apply, it's more like 10.000 cycles for flash.

The easiest way to prepare a datatype to be stored as bytes is to use union like follows:

union Converter{
  uint32_t ui32;
  byte eeprom_bytes[4];
}convert;

void convert_for_eeprom (uint32_t your_number) {
  convert.ui32=your_number;
  // convert.eeprom_bytes contains the 4-byte represenstation of your number, write those to eeprom
}

uint32_t convert_from_eeprom () {
  // read four bytes from eeprom and assign those to convert.eeprom_bytes
  return convert.ui32;
}

Note that this isn't a type conversion and the value of convert.eeprom_bytes are not meant to be processed, as they are simply interpreted as if they were a four-byte array, indeed those bytes contain "dumb" values. This way you can "convert" any datatype for byte-wise storage and read-back respectively.

Another option to convert a 32 bit integer to 4 bytes is by using bit-wise operations:

uint32_t your_number=100000;
byte b1=your_number;
byte b2=your_number>>8;
byte b3=your_number>>16;
byte b4=your_number>>24;

But this only makes sense for integers and I suggest taking a look at union.


How many pins does this circuit (HMC5883L) use?

Below image is the answer to your question.

According to this image, magnetometer required four pins of arduino.

GND of magnetometer ----> Arduino GND

Vcc of magnetometer ----> Arduino 3.3 Volt

SDA of magnetometer ----> Arduino Analog Pin 4

SCL of magnetometer ----> Arduino Analog Pin 5

A4, A5 on Uno are SDA, SCL, required for hardware-based I2C.

I hope it will help you.


How do I directly access a memory mapped register of AVR with C

It's worth exploring how PORTD is defined in the actual AVR header file.  The relevant file is iom328p.h, and it's defined as:

#define PORTD   _SFR_IO8(0x0B)

_SFR_IO8 is defined as

#define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)

and

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

This shows that 0x0b is not the address of the PORTD register, but its offset from the address __SFR_OFFSET, which is 0x20.  Indeed, if you look at the ATMEGA328 datasheet, the register summary shows that PORTD is at offset 0x2b.  So that is the address that you would want to access via a pointer.

Note that this also shows the type of the pointer, if we fully expand the original definition of PORTD we get:

#define PORTD   _SFR_IO8(0x0B)
#define PORTD _MMIO_BYTE((0x0B) + __SFR_OFFSET)
#define PORTD _MMIO_BYTE((0x0B) + 0x20)
#define PORTD (*(volatile uint8_t *)(0x2B))

This syntax takes the integer 0x2B, casts it to type pointer to volatile uint8_t, and dereferences that pointer so you can assign to or read from the location the pointer references.  The volatile qualifier is important because it prevents the compiler from optimizing out accesses to memory.  Without it, the compiler may store the value to a register instead, or not store it at all, which would mean your IO port would remain unchanged or appear to report an incorrect value.

To go back to the title of your question, you have asked how to "directly access a memory mapped register in C", well the answer is you do that exactly the way the header file defines for you:

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

aka

PORTD = 0xff

There is no more direct way than this.  The compiler sees a literal address and writes to it.  What you've written is very different (adjusting to use the correct address and type:

volatile uint8_t * portd = 0x2b;
 *portd = 0xFF;

This allocates a location in memory symbolized by portd, which holds the value 0x2B.  When you write *portd = foo, the MCU has to access the location where portd is stored, take the value found there as an address to find the location you actually want to write to.  This method requires that you allocate a place in memory to hold portd and requires an extra memory access to be able to read or write to the port register.  This method is therefore indirect.

In reality, if optimization is enabled, the compiler may optimize the pointer away and replace it with the same literal access as in the PORTD case, however this depends on the program structure, and in particular the qualification and scope of the pointer.  Limiting the scope of portd as much as possible and/or declaring it as volatile uint8_t * const portd = 0x2b (which indicates that the pointer's value is constant even if the value pointed to is volatile) will increase the likelihood of the pointer being optimized away.

The reason the AVR headers define the IO port registers this way is because in addition to the standard load/store instructions that can access the entire data memory address space and take three clock cycles to complete, the IO registers are special, and can also be accessed using IN/OUT instructions, which complete in two cycles.  The load/store instructions use the memory address for the IO registers (starting at offset 0x20), whereas the IN/OUT instructions use the IO address, which starts at 0x00, but corresponds to 0x20 in the memory address space.  From the datasheet:

So when you access an IO location, the optimizer should recognize that it can issue a more efficient instruction than the standard load/store, and it will replace the load/store to 0x2b with an in/out to 0x0b.


SdFat library Change output style of sd.ls(LS_R)

I am currently trying to have fun Modding my own sd.ls().

Worst way, modifying the library:

Go into FatFilePrint.cpp

(Suggestion: Create yourself a new 'flag' like LS_COMMA)

Find the line

void FatFile::ls(print_t* pr, uint8_t flags, uint8_t indent) { ...

add your flag

if (flag & !LS_COMMA) {
   pr-->write(':');
} else {
    //original library set of
    // pr->write(stuff);
}

--> SuperClass version # (prefered )

this will override the original ls() method by creating a new Class inheriting from the original one.

rather then invoking it from "volume",
    sd.ls( your params);

invoke it from a directory file instead.

superFatFile rootDir;
rootDir.open("/");
rootDir.ls( __your_params__);

Place this superClass declaration in your .h
don't hesitate to remove any of the "flags" related code if YOUR requirement never calls for them.

class superFatFile : public FatFile {
    public:
    void ls(print_t* pr, uint8_t flags /* = 0 */, uint8_t indent /* = 0 */){
        superFile file;
        rewind();
        while (file.openNext(this, O_READ)) {
            if (!file.isHidden() || (flags & LS_A)) {
                // adds 'spaces' indent for dir level
                for (uint8_t i = 0; i < indent; i++) {
                    pr->write(' ');
                }

                if (flags & LS_DATE) {
                    file.printModifyDateTime(pr);
                    pr->write(' ');
                }

                if (flags & LS_SIZE) {
                    file.printFileSize(pr);
                    pr->write(' ');
                }

                // prints filename
                if (!file.isDir()) {
                    file.printName(pr);
                    pr->write('\r');
                    pr->write('\n');    // HERE IS YOUR SEPARATOR CARACTERS !!!
                }

                // execute recursivly if LS_R flag was set
                if ((flags & LS_R) && file.isDir()) file.ls(pr, flags, indent + 2);

            }

        }
        file.close();
    } // end of new LS method
}; // end of superClass


Bluetooth serial readings on 0.96'' Adafruit OLED

Instead of BTSerial.read(); there should be

String content = "";
char character;

while(BTSerial.available()) {
     character = BTSerial.read();
     content.concat(character);
 }

and then you send content to lcd by putting

display.write(content);


How many bluetooth modules can be interfaced with Arduino UNO?

Two. One on the hardware UART (TX/RX pins with the Serial object). One on SoftwareSerial on any two pins you choose.

Any more than that and you will need more hardware UARTs.


Arduino is not recognized by any computer

The reason that it is not connecting can be anything from wrong driver installation to the dead Atmega 16u2 chip. But I must exclude the former option as you said you'd tried on different OS and different computers. So double check the driver installation. And if does not work try to find out whether Atmega16u2 is fried or not. One solution might be to reflash the original firmware through an external ICSP programmer. If don't have any programmer but another arduino uno you might try out the gamon's tutorial on flashing firmware on the little USB to serial interface chip.
Anyway if your arduino is new and official you can get the right support online on arduino.cc. but if it is a clone you may try to contact the reseller whom you bought from.


The if(delay1>10) does not have the conditional code in {}, so it should look like

if(delay1>10) {
//conditional code, what happens if statement == true
}

And if I understood your project and code correctly, when delay1 <= 10 then you want the led3 and led4 to light up. So you want to add an optional else{} block. This optional block will be skipped, if the if statement is executed. If the if statement is not executed, because for example your delay1 is smaller or equal to 10, then the else block will be executed.

else{
//led3 and led4 light up
}


There is an Arduino Eclipse plugin named sloeber! And Eclipse is an awesome cross-platform open-source IDE!

Stino is good. It requires Sublime Text 2 which has an indefinite free trial.

Visual Micro provides a full build system with debugger for Arduino in Microsoft Visual Studio. For advanced users it also allows the underlying Arduino source code to be viewed or modified, enabled projects and/or libraries to be edited from any location and shared in multiple projects alongside true cross-platform intellisense.

For more go to The Official Arduino Site

For development on Windows, there is a special edition from Arduino official IDE called arduino-erw, This edition much better the last one because it fixed a lot of lagging and stability issues!


The PIR can’t provide enough current to drive the led. The maximum current for the BIS0001 is 10mA.

Either increase the resistor value, and accept that the led is less bright.

Or use a transistor to drive the led.

Or connect the led to an Arduino pin and turn the led on by code, based on the input pin connected to the PIR


I had same problem and I think I have solved it.

In boards.txt file, I had:

##############################################################

diecimila.name=Arduino Duemilanove or Diecimila

diecimila.upload.tool=avrdude diecimila.upload.protocol=arduino

diecimila.bootloader.tool=avrdude diecimila.bootloader.low_fuses=0xFF
diecimila.bootloader.unlock_bits=0x3F
diecimila.bootloader.lock_bits=0x0F

diecimila.build.f_cpu=16000000L diecimila.build.board=AVR_DUEMILANOVE
diecimila.build.core=arduino diecimila.build.variant=standard

## Arduino Duemilanove or Diecimila w/ ATmega328
## --------------------------------------------- diecimila.menu.cpu.atmega328=ATmega328

diecimila.menu.cpu.atmega328.upload.maximum_size=30720
diecimila.menu.cpu.atmega328.upload.maximum_data_size=2048
diecimila.menu.cpu.atmega328.upload.speed=57600

diecimila.menu.cpu.atmega328.bootloader.high_fuses=0xDA
diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05
 diecimila.menu.cpu.atmega328.bootloader.file=atmega/ATmegaBOOT_168_atmega328.hex

diecimila.menu.cpu.atmega328.build.mcu=atmega328p

## Arduino Duemilanove or Diecimila w/ ATmega168
## --------------------------------------------- diecimila.menu.cpu.atmega168=ATmega168

diecimila.menu.cpu.atmega168.upload.maximum_size=14336
diecimila.menu.cpu.atmega168.upload.maximum_data_size=1024
diecimila.menu.cpu.atmega168.upload.speed=19200

diecimila.menu.cpu.atmega168.bootloader.high_fuses=0xdd
diecimila.menu.cpu.atmega168.bootloader.extended_fuses=0x00
 diecimila.menu.cpu.atmega168.bootloader.file=atmega/ATmegaBOOT_168_diecimila.hex

diecimila.menu.cpu.atmega168.build.mcu=atmega168

##############################################################

I have replaced the line containing:

diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0x05

with:

diecimila.menu.cpu.atmega328.bootloader.extended_fuses=0xFD

Everything is ok now.

I can install boot loader on an ATMEGA328P (with an usbasp programmer), and I can install sketchs after that (via usb serial).

I don't know if it's the best way to solve the problem, but it works.
Hope this will help you, if not already solved.


How do I add dimming control to my following LED toggling program on Arduino? Also how do I improve my existing code?

How do you improve your code?

Firstly there is nothing disastrously wrong with you code, it could do with a polish, but who's code couldn't?

In the dim and very distant past I was told "you write code once but read it many times" so try and make your code readable and clear.

If the values aren't going to change then they should be constants or #defines.
ALWAYS initialise variables.  (Doesn't matter on an Arduino because the compiler does it for you, but its good practice).
Boolean should be true or false.
You are writing C/C++ not Java.  Opening braces { should be on a new line.  It makes the code easier to read and match up the braces.
Unless your space bar is broken, put spaces after commas and either side of equals.
Using function parameters and less global variables will make you code more reusable.  Imagine the day when you start a new project and copy and paste functions from previous projects and finish the code in 15 minutes.
One statement per line.  cwState = wwState = HIGH;.  In this case its not a problem, but you can get into states where side affects screw everything up.  Also its easier to read.
Comment the code as you go, because you'll never go back.
Explain what each function does, because you'll have forgot by
tomorrow.

I hope that helps you write better code and none of it has caused offence.


Platform-independent functions for FastPWM?

It is highly unlikely there would be direct 1:1 functions that implement such discrete operations. Simply because such operations are pretty unique to a single family of microcontrollers. They are too low-level for an API to even consider wanting them.

Instead, there are higher level functions which may, if the chip requires it, include those operations.

The operations you list are all related to PWM, so the higher level function that would encompass them would be analogWrite().


I often unsolder the female connectors to solder wires directly. I would simply unsolder then and solder male headers in their place.


pardon me if i asked too soon. I found the answer.
all verb are supported. but post and get got their own names.

 int httpCode = http.sendRequest("PUT", String(data));

enven post method implement the sendRequest.


Is it possible to measure analog output?

First: Why would you need to measure the PWM value. You already know it; it's saved in the val variable. Why not just use this variable for later use in code?

Second: Doing the analogRead on the same pin as the PWM output is not going to work. Internally there are 2 different hardware peripherals, that are responsible for these functions: The ADC is responsible for measuring analog voltages, while one of the Timers is responsible for generating the PWM output. Only one of them can connect to the pin at any time. Thus you are not measuring the PWM signal, when you do an analogRead(pwmPin). This function set's the pin for measuring analog voltages (means it connect it to the ADC and configures the ADC) and thus disconnects the Timer hardware.

Third: Doing an analogRead() directly on a PWM signal is not going to work. PWM is still a digital signal, so measuring it's analog voltage would yield only values around 0 and 1023. This signal is transformed to a real analog voltage through a low pass filter, either electrically or mechanically (here I mean because mechanical elements often cannot follow the relatively fast PWM signal - like a motor or a speaker - which results effectively in a low pass filter).

How to measure a PWM signal then? First you definitely need to use a different pin, than the PWM output pin. Then you have 2 ways of measuring the current PWM value:

You can connect the PWM output to a low pass filter (combination of resistor and capacitor; you can google this and get very detailed descriptions), and the output of the low pass filter to an analog input pin of the Arduino. Then you can do analogRead()s to measure the current value.
You can measure the PWM signal directly, meaning measuring the actual pulse width of the signal. There are multiple ways of doing this, one being the pulseIn() function, which wait's for a pulse to complete and returns the length of the pulse.


How do I connect two slaves of same type in I2C?

The problem is with the magnetometer:
"The HMC5883L has a fixed I2C address, you can only connect one sensor per microcontroller!"
Wiring and Test

Also, it says it in the specs on page 2:
 I2C Address
8-bit read address 0x3D
8-bit write address 0x3C
3-Axis Digital Compass IC HMC5883L

Low cost magnetometers appear to have fixed I2C addresses. One solution would be to get a different one in addition to yours. For example, the MAG3110 has I2C address 0x0E and the FXMS3110CDR1 has I2C address 0x0F.
Xtrinsic MAG3110 Three-Axis, Digital
Magnetometer

More information on this page:

How to connect multiple of the same device to an Arduino using I2C?

P.S. You are more likely to get an answer to your second question by posting it separately (and help others in the process).


Arduino 2560 as an Interface to 4 Serial Hardwares

No, but it is possible to use 3 of them. The reason being that one of them is the connection to the computer.

The hard part is in the programming. You will need not only a suitable sketch on the Arduino (the easy part), but also some software on your computer that presents three COM ports to the operating system and forwards the data through to the Arduino in a suitably packeted format, and receive data back and sent it on to the right COM port.  Depending on your operating system that may be a very easy task (on Linux and OS X) or a complete and utter nightmare (Windows).


Arduino Uno Wunderground weather station - Ethernet connection failed

I assume u used a W5100 shield. This shield is capable of having 4 connections open. If the connections are not closed for some reason the chip is unable to make another connection.
This means after sending u need to close the connection. (else it will work 4 times).

ethernetClient.stop()

Just before or after

Serial.println("New data uploaded");

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


Arduino based fully controlled aquaculture

I would suggest finding sensors that work on an I2C bus. This way all the sensors are only using two pins for data. That will free up other outputs for motors, heaters that will probably be on relays or other drivers that need a single or multiple pins for each devices.  As you start to plan it out, if you do run out of pins on a arduino uno, look at the Mega, as it has many more GPIO pins as well as multiple dedicated UART ports.

Bottom line, find your sensors, drivers, see what type of communication they require, and start to make a list of how many separate io pins you need. Then that will tell you which board is suitable for your project.


Sending a text message through a arduino wifi shield

Sending an email you need a network connection of some form.  Options include:

Ethernet Shield
WiFi Shield
GSM Shield (can be expensive, but will work almost anywhere)

To send a text message you need access to a text message service. That can either be directly through a mobile phone operator or through an on-line SMS gateway service. For an on-line service the options are as above, since it's almost the same as sending an email (in fact, some gateways offer an email-to-SMS gateway option). For direct mobile provider access you can only use a GSM shield.

So really it boils down to how mobile you need it to be, and how much you are willing to spend (both on the initial hardware outlay and service provider fees and charges).


How can I increase resolution for current sensor?

In default configuration, the Arduino's ADC has a range of 0v-Vcc (5v or 3.3v depending on the model). If you are sure your input voltages will always be way lower than Vcc, spreading the ADC's resolution over that range is a waste of accuracy. What you need to do is to properly configure your analog reference voltage.

Basically, this is a way of telling your Arduino "instead of spreading your ADC's bits over a range of 0v to Vcc, just cram all that accuracy between 0v and [refVoltage]."

So:

Measure the highest analog output your sensor will give.
Setup a voltage divider to output a little more than that
Connect the voltage divider's output to the AREF pin
in setup(), declare analogReference(EXTERNAL);

And that's basically it. As noted, in this specific case you'd probably be better off buying another sensor altogether. However, you won't always have that luxury, and knowing how to set the analog voltage reference always comes in handy.


ESP01 to DC Motor powered via Battery with Power Regulator

It's not clear what you mean with "adapter to regulate voltage".

Typically, one would use some form of driver.

The TB6612FNG, for example, comes on PCB, both as standalone and with additional chip with I2C interface, like this one: https://wiki.wemos.cc/products:d1_mini_shields:motor_shield

It is very convenient if you need to use multiple motors, as you can have several configurabe I2C addresses, and each driver has 2 channels.


I just removed the ENE(+) pin of the driver, which was connected to the +5V. Now it's working and the stepper is rotating.

I just got a hint from this video.


Why the command noDisplay() clear all LCD screen?

I tried out your code. It's working absolutely fine.

Whenever lcd.noDisplay() executes then LCD not displaying hello, word!...
And whenever lcd.display() executes then LCD displaying hello, word!...

So, that's why "hello word" not continuously displaying.

And you can also find the display() and noDisplay() functions to turn on and off
the display comment on top of arduino sketch.


From the Amazon page you linked to:

  1 dc+ : Dc power supply positive pole
  2 dc- :Dc power supply negative pole (i.e. ground)

Arduino:
VCC: positive DC power supply
GND: ground

technically, VCC = the voltage at the collector of a transistor, these days it's used as shorthand for the positive output pin of an IC.


Using 2 RGB lights over Bluetooth with a DigiSpark

Which means, analog connections.

Nope. It means PWM.

How would you control the brightness of a single LED?

By generating a PWM signal with:

sufficiently high frequency to not be able to notice the flickering;
duty cycle proportional to the brightness you want/need, where 100% is full brightness, and 0% is OFF

You only have to do that for each colour of the RGB LED you want to drive.
Ideally you would use a HW block capable of generating the PWM signal, but it can be also bit-banged, should you run out of PWM blocks.

Just keep in mind that different colours have different currents (for the same level of brightness), so you have to pay attention at calculating the correct value of the resistor applied to each colour.

If you prefer to ensure that each channel is driven by a HW PWM generator, you can also use an external driver. Ex: I2C 6-channels PWM generator.


Communicating Via Serial1 on Arduino Mega

If you take a look at the headers on the Mega, you'll notice that one of them has labels of "RX1" and "TX1" through "RX3" and "TX3". You'll also notice that the XBee shield does not connect to that header, therefore you cannot use Serial1 through Serial3 with the shield. Either switch to a breakout board that you can connect manually or stick to software serial.


Leonardo (32u4): ways to brick it programmatically

If you upload a program that changes the speed of the USB core it would be almost bricked. What would happen is this:

Power on, boot loader starts, USB device enumerated on PC.
A few second later program start, USB core speed changed, USB device disappears from PC

The issue here is that not only do you have to hit reset to program, after the reset you have to quickly select the right com port and then upload before the program starts.

The Redbearlab Blend Micro requires a USB core speed to be set in the user program. In their setup instructions there is a step to edit the Arduino main.cpp and add a section to do so. If this step is missed, the above problem happens.


Trying to instantiate a DS3231 real time clock within a library

You appear to be providing a pointer to a constructor, not to an object.  Either create a new object with new, or instantiate the object separately and provide the pointer to the object:

_realTimeClock = new DS3231(SDA, SCL);

Better still, extend the existing class and implement your own methods:

clsss JBP_DS3231 : public DS3231 {
    public:
        JBP_DS3231(uint8_t d, uint8_t c) : DS3231(d, c) {
            String thisTime = "";
            Serial.println("About to try to get time from RTC."); // Last line we hear from.

            thisTime = getTimeStr();
            Serial.print("Time in constructor is: ");
            Serial.println(thisTime);
        }

        String TimeStamp() {
            String timeStamp = "";

            Serial.println("In TimeStamp().");
            timeStamp = getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
            Serial.print("Value of timestamp is: ");
            Serial.println(timeStamp);
            timeStamp.concat(" ");
            timeStamp.concat(getTimeStr());
            Serial.println(timeStamp);

            return timeStamp;
        }
};

void setup() {
    Serial.begin(115200);
    JBP_DS3231 myRTC(SDA, SCL);
    Serial.println(johnsRTC.TimeStamp());
}

void loop() {
}

(Note: untested)


RFM69HCW 915 MHz radio module: Sending a stream of int values rather than char[ ]

You need to send the address of a buffer and the size, in bytes, of that buffer. What that buffer consists of is neither here nor there.

If you have an array of 10 ints you have a 20 byte buffer (since one int is 2 bytes on an 8-bit Arduino).

So you just pass it the address of the buffer (which as an array it is already just an address) and the size of that buffer:

int values[10];
// whatever to fill the array
RFM69::sendWithRetry(20, values, 20, 4, 1000);

As long as the array is statically created (e.g., a global variable with a fixed number of entries) you can use sizeof() to get the size in bytes:

RFM69::sendWithRetry(20, values, sizeof(values), 4, 1000);

As long as you receive at the other and using the same type of buffer it should be completely transparent.

To keep the system cross-platform and able to run on an Arduino that is either 8 or 32 bits and have them completely interoperable it is best to use variables with a fixed size. Instead of int use int16_t which is always 2 bytes and signed on every platform everywhere:

int16_t values[10];

Or use uint16_t if you want it unsigned.


Can you help me combining these sensor sketches as one in Arduino

Variable renaming

Rename thresholdValue in the first two sketches to rainSensorThreshold, and lightSensorThreshold respectively, and sensorThres to smokeSensorThreshold in the third sketch.

Rename sensorValue in the first two sketches to rainSensorValue, and lightSensorValue respectively, and analogSensor to smokeSensorValue in the third sketch.

Change the Analog pin
Use A1 (or some other analog input other than A0 or A5) for ldrPin in the second sketch, for example:
int ldrPin = A0;

Consistant LED pins
Use the same pins in the third sketch, as are used in the first two sketches, for the two LEDs and note the change in case:
int greenLed = 11;
int redLed = 12;

to
int greenLED = 6;
int redLED = 7;

Recompile each sketch
To check that the each sketch still works, recompile each one separately.
Combine the code
Finally... Splice the code together appropriately, keeping the three parts separate:

Global variables
setup()
loop()


It is actually slightly confusing owing to the (actually redundant) & 0xff in there.

What is happening is first the address is right-shifted so as to place the byte of interest at that moment in the lowest 8-bits (address >> 16 for instance to get bits 16-23 moved to bits 0-7) and then the lowest 8 bits are masked off by ANDing them with 0b11111111 (0xFF). This removes any bits that are above the 8 bits we are interested in - however the fact that it's cast to uint8_t and also passed to a function that expects uint8_t makes that masking redundant. Any bits above the first 8 are discarded anyway.

So to take an example address of, say, 100,000 (which is 0x186A0 in hex) and run those three commands on it, we end up with:

SPI.transfer((uint8_t)(address >> 16) & 0xff);

0x186A0 >> 16 = 0x00001
0x00001 & 0xFF = 0x01

SPI.transfer((uint8_t)(address >> 8) & 0xff);

0x186A0 >> 8 = 0x00186
0x00186 & 0xFF = 0x86

SPI.transfer((uint8_t)address);

(uint8_t)0x186A0 = 0xA0

The end result as you can see is three SPI transfers each sending a single byte:

0x01, 0x86, 0xA0

And that corresponds to the protocol for that chip, which is basically:

<Command>, <Address H>, <Address M>, <Address L>, <Data>...

For instance:

0x02, 0x01, 0x86, 0xA0, 0x69

You send the "WRITE" command, send the three bytes of the address you want to write to, then follow that with the data to write. Or you send the READ command, send the three bytes of the address you want to read from, then the data is returned to you a byte at a time.


Blank project gives errors while uploading Arduino Leonardo on Linux Manjaro

Okay I found a way to do this.
Open Terminal and type:

ls -l /dev/ttyACM*

you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is dialout (is the group owner of the file).

Now we just need to add our user to the group:

sudo usermod -a -G dialout <username>

So for me that would be:

sudo usermod -a -G dialout john

BUT it seems to work with dialout on ubuntu/debian based distros. I am on Manjaro and instead of dialout I had to use uucp (and in general on Arch based distros) so:

sudo usermod -a -G uucp john

You will need to log out and log in again for this change to take effect.

This is the procedure to access the serial port from the Arduino Software (IDE) if you get an error

After this procedure, you should be able to proceed normally and upload the sketch to your board or use the Serial Monitor.

Although for me that wasn't over. After doing this the only error I got was Arduino IDe simply saying that it doesn't have permission to write to that port. So I had to start Arduino IDE by:

sudo arduino

in the terminal. After that everything works just fine.

I found help at those links:

https://www.arduino.cc/en/Guide/Linux#toc6
https://forum.manjaro.org/t/how-to-enable-putty-usb-serial-converter-access-without-sudo/82736


Communication arduino MODBUS fails on high number of registers

Before you decided to switch platforms, take the time to figure out what your resource usage is. After compiling you'll get a report of the amount of memory you're consuming, check that first.

After that, it would be helpful if you could describe more clearly what you're seeing when the code fails.


Multiple Buttons on Single Analog Pin and Trigger Pin Arduino Uno

Use the analog comparator in the ATmega328P to trigger an interrupt once the input voltage rises enough to indicate a button press.

Connect the analog network to both the analog input and D6.

If your lowest analog voltage is not greater than 1.2V then apply a voltage greater than 0V but more than 40mV less than your lowest analog voltage to D7. If you have not connected the voltage then configure the comparator to use the internal bandgap reference (ACSR |= _BV(ACBG)).

Enable the comparator interrupt and capture on a rising edge (ACSR |= _BV(ACIE) | _BV(ACIS1) | _BV(ACIS0)).

Disable the digital input on D6 (AIN0), and on D7 (AIN1) if connected to a voltage reference (DIDR1 |= _BV(AIN0D), DIDR1 |= _BV(AIN1D)).

Write an ISR that does what you want on comparator trigger (ISR(ANALOG_COMP_vect) { ... }).

Now go back and read all that three more times until you understand it. As always, see the ATmega328P datasheet for details.


How to stole/read data from an output serial port?

This device seems to communicate via SPI. Google for "serial peripheral interface" and learn how it works. You will then be able to know what to do with the information in chapter 4 of the datasheet.


By default the fastLed is limiting the refresh rate to 400 fps (i.e. 2.5ms).
You can disable that with FastLED.setMaxRefreshRate(0);


Thanks for the heads up that the GET request was indeed the right way to go. I managed to work through this a bit today got the GET request to work. I also hooked up the button and got that to send the two requests on both press and release. I know this code is for the Photon but I hope it'll help someone else out

// TCPClient
#define LIB_DOMAIN "10.0.1.252"
TCPClient client;

// This constant won't change:
const int  buttonPin = D1;    // the pin that the pushbutton is attached to
const int ledPin = D7;       // internal LED pin

// Variables will change:
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  pinMode(ledPin, OUTPUT); // Initialize D7 pin as output
  pinMode(buttonPin, INPUT_PULLUP);
  // Initialize D1 pin as input with an internal pull-up resistor
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, turn on or off
    if (buttonState == HIGH) {
        digitalWrite(ledPin, LOW);
        //TCPClient
        client.connect(LIB_DOMAIN, 80);
        client.println("GET /control?cmd=event,TurnOff HTTP/1.0");
        client.println("Host:" LIB_DOMAIN);
        client.println("Content-Length: 0");
        client.println();
    } else {
        digitalWrite(ledPin, HIGH);
        //TCPClient
        client.connect(LIB_DOMAIN, 80);
        client.println("GET /control?cmd=event,TurnOn HTTP/1.0");
        client.println("Host:" LIB_DOMAIN);
        client.println("Content-Length: 0");
        client.println();
    }
    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

}


Arduino One Wire Bus DS18B20 self developed driver missing bits or extraneous bits

I managed to find the bug and fix it.
I was missing that after the reset pulse the master must be in RX mode for atleast 480us no matter what, even if the presence pulse did occur and even if it's rising Edge did appear already. This mistiming did lead to the missing bits that were corrected with sending more bits until now (which in turn lead to the extraneous bits later on in the transmission).


When the reset pin of Uno is connected to ground, the Uno resets. That is what the reset button does.

You connected the reset pin of Uno to other device's reset pin. If the reset pin of the other device grounds the reset pin of Uno (grounds or has lower then required voltage), then Uno resets.

The reset pin of a peripheral device is intended to reinitialize the device by program running in microcontroler by setting a connected GPIO pin to required state.

If you have a library for the device, that library will take care of the GPIO pin controlling the reset of the device.

If you plan to use the device without library, then you should take care of the reset pin in your sketch. Setting the selected pin to OUTPUT and initializing it to required state.

The usual required state for reset is LOW so the output must be HIGH for the device to work.

Some tutorials and libraries require connecting the reset pin of gsm800l to a selected Uno GPIO pin with a transistor, and then reset is HIGH and LOW is for normal operation.


I see several issues here.

The most serious is in the wiring of the Arduino. The first argument of
attachInterrupt() is an interrupt number. On the Uno, “interrupt 0” is
wired to the pin “digital 2”. This is where you should connect the
output of the zero-crossing detector (ZERO_OUT).

Then, as noticed by Juraj, there is the issue of the interrupt handler
taking too long to execute. This is generally considered bad practice,
and it has some negative consequences on the working of the Arduino core
like, e.g., the millis() function will be completely off. I do not
think, however, that this is a serious issue for you. There is one
single time-critical bit in your program, which is the generation of the
triac trigger pulses. You really do not care about millis() or any
other time-related things. Thus, at least for the initial version of the
program, I would not care too much, and just let the interrupt handler
delay as needed.

The third issue has been noted by chrisl in a comment: there is a race
condition with both the main program and the interrupt handler accessing
the same output variable. Race conditions are a nasty kind of bug
because usually things work fine “most of the time” and then fail at
unexpected times. I would not recommend, however, to run
myPID.Compute() with interrupts disabled: that may throw off the
timing of your triac pulses. Instead, compute the delay required by the
interrupt, save it to a temporary variable, then copy it to a variable
shared with the handler. Only the copy needs to be done with interrupts
disabled, and that takes only a handful of CPU cycles:

// Variable used by zero_crosss_int().
// Do not forget the `volatile' qualifier.
volatile int dimtime;

void loop() {
    // PID and associated computations.
    set_value = map(analogRead(A1), 0, 1023, 150, 400);
    input = map(analogRead(A0), 0, 550, 25, 400);
    aaa_PID.Compute();
    int tmp_dim_time = 75*output;

    // Critical section executed with interrupts disabled.
    noInterrupts();
    dimtime = tmp_dim_time;
    interrupts();
}

Edit: If things do not work, you should try to debug piece by piece.
Sending debug messages to the serial port should help, although serial
communication is likely to be significantly slowed down by the
long-running interrupt handler. As an alternative, you can use the triac
control pulses as a debug aid, maybe with the heating element unplugged.
For example:

In loop(), set dimtime to a value proportional to set_value.
Turn the pot and look at the FIRING_PULSE signal. Does the pulse
width vary proportionally to the pot position? Is it in sync with the
Vin zero-crossings?
Set dimtime proportional to input. Heat the thermocouple by some
external means. Does FIRING_PULSE vary as expected?
Set dimtime proportional to output, but keep the heating element
unplugged. How does the pulse change as you move the pot or heat the
thermocouple?


Difference between void setup() and void setup(void)

Absolutely nothing, in modern versions of C and C++. Specifying no arguments is the same as specifying void.

In old versions of C a function with no arguments took a single implicit int argument or allowed you to specify the arguments on a separate line, but no one uses anything like that nowadays.


How much time does the Arduino need to call a Function or to read a Variable?

It is hard to give a general answer, as it depends on the specifics of
your code and on how the compiler compiles it:

  How much time does an Arduino Uno or Mega need to only call a function.

This can involve a number of things:

the caller puts the arguments on some predefined CPU registers, unless
they are already there from a previous operation (the compiler tries
to optimize the code so that this happens whenever possible)
the caller issues the call instruction to do the actual function
call
the callee pushes some CPU registers into the stack in order to use
them without clobbering the caller's data
the callee does its job
the callee pops the previously pushed registers
the callee issues the ret (meaning return) instruction
the caller finds the return value in some CPU registers

On the Uno, the call and ret instructions cost 4 CPU cycles
each (0.25 µs). On the Mega, it's 5 cycles (0.3125 µs)
each. push and pop are 2 cycles each, and you need one such
pair for every 8-bit register you need to save.

  And how does the time change if this function is inside a Class, for
  example inside a Library?

The only difference is that a class method receives an extra hidden
parameter called this. Except if it's a virtual method, which is more
expensive because it involves some pointer dereferencing.

  How much time does a micro-controller need to read a declared
  variable?

“Reading” generally means transferring the contents of the variable to
some CPU registers. Local variable are usually allocated to CPU
registers in the first place, so there is no need to read them. Global
(and local static) variables are stored in RAM, and reading them takes
2 cycles per byte (e.g. 4 cycles for a 16-bit int).

  How to determine this values?

Disassemble the code generated by the compiler. Then look up the
instructions in the instruction set manual: it documents the number
of clock cycles needed by each instruction.


Changing pins used in ArduinoISP example

You can't change the pins.

ArduinoISP uses the SPI interface on pins 10-13 which is provided by the underlying AVR hardware.


I can't use buffer without printing in my Nodemcu esp8266

The Serial printing creates a delay. That delay enables to collect more characters in the buffer. If you read the input in small pieces (3 to 10 bytes) then the buffer doesn't contain the searched substring because it splits into two subsequent buffers. Even if you could read full buffers, it still can happen that the search string will be split.

To search for a string in a stream of data you can use function find(string). The networking Client class inherits this function from Arduino Stream class. find will read the stream until it finds the searched string. Then the next read from the stream will read the data right after the searched string.


Industrializing Arduino - 24V io? (Electronics)

You mentioned 2 items: the supply voltage to the Arduino and scaling up to 24V output.

If the supply voltage you have available is 24V, then I would suggest you look for a DC-DC converter that scales down to 12V. Or, if you are looking to design your own PCB then perhaps use a 78xx voltage regulator. The 78xx are 3 pin devices and only require 2 caps to operate - I suppose a heat sink will not be needed.

To scale up the outputs to 24V I would suggest one of the following options:

a) Relay board /
These will take the 5V from your Arduino and close a mechanical switch. If the relays are good quality they will go on for ages. And you can switch loads from 0 to 240V and more, DC or AC.
Plus of the relays are sturdiness and that they are quite forgiving for short current overloads. Minus are that relays are " slow" when compared to semiconductors and they can arce when the contacts open - especially when driving inductive loads and that. Arcing will wear down your contacts and in extreme cases generate EMI that might interfere with your electronics. Arcing can be remediated in AC with a capacitor accross the contacts or in DC with a flyback diode.

If you will make your own PCB don't forget the flyback diode on pins connecting to the relay coils or you will possibly fry the Arduino due to a voltage spike!

Many of these boards are available on the web, so it's a quick solution.

b) Optocouplers /
Also a good option. Functionally they act as a relay. They are a bit less forgiving to current overloads, so chose them wisely.
They are silent and fast acting. Available for AC or DC and up to 600V.
Minus side is that the tend to be a bit more expensive than relay boards. I'm talking about industrial grade devices and not some el-cheapo web site :-)

c) MOSFETS or Bipolar transistors /
If you are designing your PCB then this could be an option.
Here you can use a MOSFET or a PNP transistor of the adequate ratings and you would be done. Though maybe considering yur time investment the options above could be less expensive in the end.
I this case you get complete control of PCB layout which might be a consideration.
If you go this way, don't forget to add a flyback diode to the output of these devices to protect from spikes when switching inductive loads (= motors, solenoids).

A big advantage of Relays and Optocouplers is the galvanic isolation they provide, both from the load to the board as between the loads themselves.

If you could supply more detailed specs of the loads, environments etc I can help you narrow down your choices.


Why is my pushbutton always reading LOW?

The pins on each side of the button are shorted, the "button" is between the sides of the button. Else your code looks alright.

Edit: Here's an image which shows how a push button is connected internally, make sure you're using the correct pins.


Help choosing an ESC for a 500W/60V motor

I would suggest you study Brushless 3 phase DC motors.  It would take a book to explain how to do it.  You will be creating three separate synchronized phases 120 degrees out of phase.  That is not easy to do.

Try this link for a start: https://www.youtube.com/watch?v=E3BS8CO9APA
This is also good: https://www.youtube.com/watch?v=WyQInXjpGwU  Sorry I did not find part 1.

After you get through these and a few others you find I am almost certain you will pick another controller if you do the project.

Good Luck,
Gil


Force TCNT to stay below OCRxA on ATmega328P

Can I manually jump to an ISR regardless of its "normal" trigger?

This should be possible, but is probably not the best solution.

  This is certainly an X -> Y problem, so I'm open for other
  approaches.

It would seem you are using the timer in CTC mode. In this mode, when
you write to OCRxA, the register is updated immediately, which leads
to the problem you are experiencing. The solution is to instead set the
timer to “fast PWM” mode. In fast PWM mode, the OCRxA register is
double buffered: you will be actually writing to a buffer register, and
OCRxA is automatically updated from that buffer on the same timer
clock cycle that clears the counter.

It may sound counter-intuitive to use a PWM mode when you do not need
the PWM feature. However, as long as the “compare output mode” is set to
“normal port operation” for both channels, the timer will not generate
any PWM output, and you can legitimately use the fast PWM mode only for
its double buffer feature.


Executing multiple functions/commands on Arduino

Ended up going with something like this:

#include <RFduinoBLE.h>

// State properties.
int state = 1;
char command;
String hexstring;

// RGB pins.
int redPin = 2;
int grnPin = 3;
int bluPin = 4;

// Setup function to set RGB pins to OUTPUT pins.
void setup () {
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);

  // This is the data we want to appear in the advertisement
  // (the deviceName length plus the advertisement length must be <= 18 bytes.
  RFduinoBLE.deviceName = "iOS";
  RFduinoBLE.advertisementInterval = MILLISECONDS(300);
  RFduinoBLE.txPowerLevel = -20;
  RFduinoBLE.advertisementData = "rgb";

  // Start the BLE stack.
  RFduinoBLE.begin();
}

void loop () {
  switch (command) {
    case 1:
      // Blink.
    break;
    case 2:
      // Fade.
    break;
  }

  //RFduino_ULPDelay(INFINITE);
}

// Converts HEX as a String to actual HEX values.
// This is needed to properly convert the ASCII value to the hex
// value of each character.
byte getVal (char c) {
  if (c >= '0' && c <= '9') return (byte)(c - '0');
  else return (byte)(c - 'a' + 10);
}

// Process each function/command.
void processCommand (int command, String hex) {
  switch (command) {
    case 'b':
      command = 1; // Set blink mode.
    break;
    case 'f':
      command = 2; // Set fade mode.
    break;
    case 'c':
      // We put together 2 characters as is
      // done with HEX notation and set the color.
      byte red = getVal(hex.charAt(1)) + (getVal(hex.charAt(0)) << 4);
      byte green = getVal(hex.charAt(3)) + (getVal(hex.charAt(2)) << 4);
      byte blue = getVal(hex.charAt(5)) + (getVal(hex.charAt(4)) << 4);

      // Set the color.
      setColor (red, green, blue);
    break;
  }
}

// Sets the color of each RGB pin.
void setColor (byte red, byte green, byte blue) {
  analogWrite(redPin, red);
  analogWrite(grnPin, green);
  analogWrite(bluPin, blue);
  delay(200);
}

// This function returns data from the radio.
void RFduinoBLE_onReceive (char *data, int len) {
  for (int i = 0; i < len; i++) {
    stateMachine(data[i]);
  }
}

// Main state machine function, which processes
// data depending on the bytes received.
void stateMachine (char data) {
  switch (state) {
    case 1:
      if (data == 1) {
        state = 2;
      }
    break;
    case 2:
      if (data == 'b' || data == 'f' || data == 'c') {
        command = data;
        hexstring = "";
        state = 3;
      } else if (data != 1) { // Stay in state 2 if we received another 0x01.
        state = 1;
      }
    break;
    case 3:
      if ((data >= 'a' && data <= 'z') || (data >= '0' && data <= '9')) {
        hexstring = hexstring + data;
        if (hexstring.length() == 6) {
          state = 4;
        }
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
    case 4:
      if (data == 3) {
        processCommand(command, hexstring);
        state = 1;
      } else if (data == 1) {
        state = 2;
      } else {
        state = 1;
      }
    break;
  }
}


ESP8266 Bootloader Firmware (on the ESP8266)

It appears to me that there must be some sort of prepackaged firmware on ESP8266 modules that allows user firmware to be loaded via the Rx/Tx pins on the ESP8266.

Indeed there is.

  If that firmware is corrupted, the ESP8266 is dead.

Well, if that firmware gets corrupted, then yes indeed the chip is dead. That's because the firmware is in ROM, not flash - and the only way it can get corrupted is for the chip to be physically damaged internally.

  I see the typical MISO/MOSI/SCK pins on the ESP8266, and I assume that they would be used to flash the bootloader itself.

No. They are SPI. SPI has nothing to do with flashing firmware. It just happens that AVR chips share the same pins as SPI for their debug protocol.

You cannot replace the bootloader on an ESP8266. It is in ROM. It's unchangeable - except as mentioned earlier by physical trauma to the silicon itself.


Industry Standard for Single-Board Computers?

Whether or not the Arduino company goes out of business isn't all that relevant. For one thing, there are now two competing companies vying for the Arduino trademark - arduino.cc and arduino.org.
The Arduino has such a ground-swell of popularity that clone boards are widely available on eBay and from other suppliers. While people are willing to buy them, someone will sell them.
The design is open-source, which makes it a safer choice than other designs who keep their design proprietary. For one thing, it guarantees that someone will make compatible boards, even if Arduino(s) fold.
The "heart" of the Arduino is (in most cases anyway) a chip from Atmel - so you really should ask if Atmel will go out of business. Probably not, but in any case, an alternative supplier might just as easily go out of business.
I wouldn't be building an "Arduino board" into a production system anyway - too much chance that wires would fall out of the prototyping sockets. However the prototyping board is good for learning about their capabilities, and testing your code.

  Do Arduinos, or any other single-board computer, come in any sort of industry-standard form factor?

I'm not aware of any industry-standard form factor. The Uno design has caused a lot of people to make "shields" that fit onto that form factor, so that is probably the closest you would get to an industry standard.


The simplest way is to unplug the ATMega328P from the board (or otherwise disable it) and just use the ATMega16U2 by connecting the ESP8266 to pins 0 and 1 of the Uno.  No programming required at all then - the ESP8266 just takes the place of the ATMega328P.

If you really want to "pass it through" the ATMega328P then you will need to make a transparent pipe for the serial data.  That would involve nominating two more pins on the Uno to be a new serial connection, and using SoftwareSerial to interface with those pins.  Then you have a simple loop which reads from one port and writes to the other, and the same in reverse of course.  Make sure you have the baud rates right.  I don't know how well SoftwareSerial would perform at the (commonly) 115200 baud the ESP8266 works at.

EDIT: (Interfacing to a 3.3-V system)

Since the ESP8266 works at 3.3V, while the ATMEGA16U2 is powered at 5V, you might need to adapt the level of the ATMEGA16U2's TXD line (which is connected to the "RX" input line of the ATMEGA328P/Arduino Uno Board), to 3.3V.

To do this, connect a  1.5 kOhm resistor between the RX pin and ground. In fact, the connection between ATMEGA16U2 and ATMEGA328P is done using an 1kOhm series resistor. This, together with the 1.5k Ohm resistor, will create a resistor divider, which converts the 5V output to 3V.

See schematics below.


Rescuing an Arduino With a Broken Setup()

You can try running the code upload command directly using a precompiled hex file.

Here is how.

Go to preferences in Arduino IDE

Set the Show verbose output during: upload option.

Upload the blink sketch. (arduino does not have to be connected)

After the compilation, check the log window at bottom of the IDE.

You will find a line like this:

E:\arduino\hardware\tools\avr/bin/avrdude -CE:\arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\xxxxxxx\AppData\Local\Temp\build918c1e88f8d0a4c453f8bdfce4cccd30.tmp/Blink.ino.hex:i

That is the actual code upload command.

Copy the command line and paste it into a windows CMD window.

Edit the COM port to match your Arduino.

Reset the Arduino and immediately press Enter to run the command line.

You may get lucky and the upload "squeaks" through.

You can also move the hex file to another folder so that it is always available for doing a quick recovery.

You could also create a BAT file so that double-click on the icon runs the upload.


Error initializer-string for array of chars is too long using ESP32 Webserver

Please check the readme: https://github.com/me-no-dev/ESPAsyncWebServer#send-large-webpage-from-progmem
You probably have to declare it in progmem without rawliteral.
const char index_html[] PROGMEM = "..."; // large char array, tested with 14k request->send_P(200, "text/html", index_html);


Arduino original motor shield can not supply enough torque to the motor?

According to the motor shield page:

  To avoid possible damage to the Arduino board on which the shield is mounted, we reccomend using an external power supply that provides a voltage between 7 and 12V. If your motor require more than 9V we recommend that you separate the power lines of the shield and the Arduino board on which the shield is mounted. This is possible by cutting the "Vin Connect" jumper placed on the back side of the shield. The absolute limit for the Vin at the screw terminals is 18V.

According to you:

  I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.

  I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.

That's a lot less than 7V.

Also, from the motor shield page:

  Max current   2A per channel or 4A max (with external power supply)

How much current does your screwdriver use?


Multiple timers with different frequencies

My suggestions would be:

Implement a class that handles the queue and timer settings and uses callbacks.
If you do not need perfect accuracy, remove the loop making the program wait and do that part just setting the timer.
digitalRead() on an output pin returns the value it was last set to, therefore you do not need to waste that extra RAM.
DO NOT wait in the ISR "process_timer()", since you might lose other interrupts! (for the Serial communication, for example)
is it neccessary to have only values above 200? if not, then don't prevent them from going below that.

--or

use a total overkill system for this situation, such as my multitasking-library arduOS that also covers a some other things.


Data transfer to and from Arduino to Raspberry Pi

Ok, without rewriting all your code, one thing I'm seeing here is a lot of sloooow string functions.

Pythons print function is extremely slow, for example. You should insert some timers in your code and see how long everything's taking. I think you will be surprised.

For a real-time application, which it sounds like this is, you need to be very careful and use timeouts and non-blocking code to make sure that everything doesn't grind to a halt unexpectedly.

You really need to re-write all this code, but I'll point out a few specific problems.

delay(20);
if (Serial.available()>0){
   ...
}

This is sloppy. If your python code does not process and return data before the 20ms elapses everything is going to go out of sync.

str_data = Serial.readString();

A look at the documentation reveals that this will only return on timeout, so this is guaranteed to block for 1s (I think that's the default), so there's another show-stopper problem. See this question for more info.

cmd = str_data.substring(0, firstCommaIndex);

This is also not sufficient. There is no synchronization between the pi and the arduino, so you have no guarantee that you won't get half of a previous transmission tacked onto the front of your data string (or worse). You need to make your own buffer and parse for the datastring. Or do some careful buffer clearing and use generous timeouts.

So TLDR; here's what you want to do (assuming you want to block while this exchange happens)

Clear the arduino receive buffer.
Send data packet from arduino.
Start receiving. Add received bytes to a char buffer.
Continuously search that buffer for your complete data packet.
Timeout after x ms. Handle the lack of returned data somehow.
If you do find the complete data packet, then process it.

On the Pi:

Poll for serial data. Add it to a buffer as it comes in.
Start deleting the oldest characters from the buffer if it's longer than 2x the longest data packet
Continuously search the buffer for your data packet. If you find it then continue below.
delete the data packet from the receive buffer.
process the data.
Send out return data packet to arduino.


Cannot control servos through 32-servo-controller on Aurduino Duamilanove

There is one connection missing - the one that powers the servo and board.

At the moment your servo board is getting a small amount of power through the RX pin - disconnect it immediately, you are damaging it.

You need to provide +5V to the +5V terminal block, and also a suitable voltage (+5V should do) to the VCC on the terminal block.


If I copy your provided code in a vim-editor you can see some strange characters. <202c>

switch (val, HEX) {
  4
  5     case 0x807FB24D<202c>:
  6       Serial.println("Stisknuto PLAY");
  7       tone(2, fre);
  8       break;
  9     case <202d>0x807FB04F<202c>:

I've removed them for you:

#include <IRremote2.h>
#include <IRremoteInt.h>

#define pinIN 11

uint32_t val;
uint32_t prev;
int fre = 0;

IRrecv remote(pinIN);
decode_results result;

void setup()
{
  Serial.begin(9600);
  remote.enableIRIn();
  pinMode(2, OUTPUT);
}

void loop()
{
  if (remote.decode(&result))
  {
    val = result.value;
    if (val == 0xFFFFFFFF)
    {
      val = prev;
    }
    prev = val;
    detekceKlaves();
    remote.resume();
  }
}

void detekceKlaves()
{
  switch (val, HEX)
  {
    case 0x807FB24D:
      Serial.println("Stisknuto PLAY");
      tone(2, fre);
      break;
    case 0x807FB04F:
      Serial.println("Stisknuto STOP");
      noTone(2);
      break;
    case 0x807F18E7:
      Serial.println("Stisknuto VOL+");
      fre += 10;
      break;
    case 0x807F906F:
      Serial.println("Stisknuto VOL-");
      fre -= 10;
      break;
    case 0x807F9867:
      Serial.println("Stisknuto OFF/ON");
      fre = 0;
      break;
    default:
      Serial.println("Stisknuta jina klavesa");
  }
}


Setting up 433 MHz Transmitter and Receiver in the same Arduino sketch using Radiohead

The answer can be found in the source code 0f RH_ASK.h (you should read the well made documentation before using this library):

  At present only one instance of RH_ASK per sketch is supported.

So you will have to write such an extension yourself, use two Arduinos or use another lib for testing.


Is it possible to have long wire connections from an NodeMCU to a servo motor or button?

A push button won't be a problem. That is a very simple change in resistance from open circuit to a few ohms. You just need a low enough resistance to force the voltage coming through weak internal pullup resistor down to ground. It looks like 22 gauge wire has about 52.7 ohms / 1000 meters.
I don't think 6 meters of 22 gauge wire will be a problem for a 5V PWM signal either. If it's a very electrically noisy environment you might want to use shielded or twisted pair cable, but it seems unlikely that would be needed.


Implement Visible Light communication using Arduino

The amplitude of the signal at the photodetector is small. Better use ADC for reading.


Reliably duplicate custom IR remote control with ATTiny85

The exact duration of the pulses don't matter much. In your example, you see that in all three recorded samples that's

about 14000 (about 9400); about 1200 (about 600); about 1200 (about 600) etc.

What matters is that nowhere you have pulses of about 900 : in other words if the receiver detects a 672 pulse it will know that it's definitely a 600, not a 1200.

So if you send exactly those values, the receiver will recognize it.


Note: This is an answer that OP originally edited into his question.

I gather the data into an array of bytes data[125].

Then I gather the relevant bytes per value and stack them together:

long var = (data[4]<<8) + (data[3]);

I shift them so the relevant bytes start first

var=var>>3;

Afterwards I mask them with the RIGHT mask

var=var & 0xFF;

For the example in my question:

long var = (data[1]<<8) + (data[0]); // I need two bytes
var=var>>1; // shift them to the right one bit
var=var & 0x7FFF; // mask it with "0111 1111 1111 1111"


Soft wdt reset error on NodeMCU (ESP8266)

The culpret is the SIM808 library. It's not written to work well with the ESP8266.

The problem lies in this function:

boolean sim808_wait_for_resp(const char* resp, DataType type, unsigned int timeout, unsigned int chartimeout)
{
    int len = strlen(resp);
    int sum = 0;
    unsigned long timerStart, prevChar;    //prevChar is the time when the previous Char has been read.
    timerStart = millis();
    prevChar = 0;
    while(1) {
        if(sim808_check_readable()) {
            char c = serialSIM808->read();
            prevChar = millis();
            sum = (c==resp[sum]) ? sum+1 : 0;
            if(sum == len)break;
        }
        if ((unsigned long) (millis() - timerStart) > timeout * 1000UL) {
            return false;
        }
        //If interchar Timeout => return FALSE. So we can return sooner from this function.
        if (((unsigned long) (millis() - prevChar) > chartimeout) && (prevChar != 0)) {
            return false;
        }

    }
    //If is a CMD, we will finish to read buffer.
    if(type == CMD) sim808_flush_serial();
    return true;
}

It has a loop that can take some time to run, and it doesn't yield() at any point to allow the ESP8266's housekeeping routines to run and "kick the dog".

Adding a call to yield() inside the while(1) loop should cure the problem.


I imagine you are using the Adafruit Library, since thats the URL of the product you posted.

If so, in RTClib.h:

#define DS1307_ADDRESS  0x68
#define DS3231_ADDRESS  0x68

And in the OBDs product page:

OBD I2C Address: 0x68

MEMS I2C Address: 0x62

Which obviously causes a conflict.

It seems that they have a fixed I2C address (some devices are configurable via software, others with external pins). So the solution would be to use other RTC, other OBD (or change its address) or use a bus splitter, or use a MCU with more than one I2C bus.


Change:

SIM900.println("AT+CMGS=\"591"numero"\"");

to

SIM900.print("AT+CMGS=\"591");
SIM900.print(numero);
SIM900.println("\"");

Note that only the final call is to println() (which just prints a carriage-return character at the end.)


How does if(serial) work, a c++ question

It's not the constructor that's returning the value, it's the bool operator:

Uno:

HardwareSerial::operator bool() {
    return true;
}

Leonardo:

Serial_::operator bool() {
    bool result = false;
    if (_usbLineInfo.lineState > 0)
        result = true;
    delay(10);
    return result;
}

When you use the object in a setting where a boolean value is expected of it (e.g., if, while etc.) the bool() operator is called (if it exists) and that value is used.

More specifically, the bool() operator is called when the object is being cast to a bool type, either implicitly (as in if...) or explicitly (as in ... = (bool)Serial;).

More on C++ class operators here: http://en.cppreference.com/w/cpp/language/operators


Connecting battery and LED to Arduino Due

What you want is something like this (ignore the fact that my mini breadboard is stuck to a shield):

My starter Arduino kit came with the connector for the 9 volt battery into the power socket on the Arduino, you may need to make one.  You cannot connect the 9V battery to any other part of the Due that I am aware of (without damaging it!).

It is perfectly safe to power your Arduino with 9V this way, there is circuitry to step the voltage down to the 5V and 3.3V that the board requires.

In the connector strip nearest this power socket (labelled Power on my board) there are a couple of Gnd connections and 5V and 3.3V connectors perfect for what you want to do.  I have used the 3.3V connector in my photo, but the 5V one should also be fine with the right resistor.

In your picture you don't appear to have anything connecting the LED to ground, but other than that, if you were to connect the battery up as I have shown and the red and black LED connectors to 3.3V and Gnd respectively, it should work as desired.

As a next step, you could load the sample sketch Examples->01Basic->Blink, write it to your Due, move the red LED connecting wire to pin 13 on the opposite side and your LED would flash (along with one of the LEDs on the Due board itself).

Edit (to specifically address your concerns):

The 9V battery will not fry the Due if it is connected through the power socket, which has circuitry to drop the voltage to safe levels.
The 9V battery will not damage the LED or resistor as they are connected to 5V or 3.3V that the Due outputs, not the 9V from the battery.
Only connect the battery through the power socket.  If you have a good quality steady 5V power supply, you can power the board through a 5V pin (at least I have been able to), but you bypass the voltage regulation circuitry that way and it is not recommended.  Connect the black wire from your LED to any Gnd pin, connect the red wire from the LED to 3.3V or 5V.

Additional edit:
You can connect the battery directly to the Arduino Due board without needing a plug to connect to the power socket.  Connect the red battery wire to the Vin pin and the black battery wire to a Gnd pin.


I found another way around the solution.

Idk if this is helpful to anyone but the problem was that I had an unknown number of nodes I wanted to loop through, Example of the json format above.

void loop(){
int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
          payload = http.getString();
      }
      if(payload.length() > 0){
          JsonArray& nodes = jsonBuffer.parseArray(payload);
          if (!nodes.success()) {
            Serial.println("parseObject() failed");
            jsonBuffer.clear();
          }else{
            int node_length = nodes.size();
            for(int i=0; i<node_length;i++){
              Serial.printf("node-%i\nValue : ",i );
              String value = nodes[i]["value"].as<const char*>();
              String state = nodes[i]["state"].as<const char*>();
              Serial.println(value);
              Serial.print("State : ");
              Serial.println(state);
            }
            http.end();
        }
    }else{
      Serial.println("Payload Empty");
    }
  }

  jsonBuffer.clear();
  delay(8000);
}


LB1847 stepper controller :how to connect to grbl atmega based board with step ,direction,enable , limit?

It seems that most people use an Arduino CNC Shield to connect their Arduino Uno (running GRBL software) to the drivers of the stepper-motors. Via Google you find plenty of them, for example: here and here. The schematics of the latter example are published here. You could use the information from this schematic to make your own 'interface' between the Arduino and the LB1847 driver chips.