I can't seem to receive data to the ArduinoStudio serial monitor on ubuntu 14.04

By default, on a linux system without specific
udev binding rules to rename the device into something non standard, the FTDI driver should map the usb to serial port on /dev/ttyUSB* and not to /dev/ttbACM*. I suspect that you were just looking in the wrong place.
I think it defaults to /dev/ttyUSB* for any usb to serial dongle:

usb-serial.c:   usb_serial_tty_driver->name = "ttyUSB";


Reading Two Quadrature Encoder using a single Arduino Due

According to Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483 and referenced excel sheet with Device to No of QDEC channels it seems to have two of them. However in DUE almost none of interesting devices are wired to headers completely (Extmem, SD interface,...)
However TIOA6 and TIOB6 should be on pins 5 and 4
Pin configuration should be something like this:
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

And TC0 is pretty much same as TC2, so just copy&paste and change TC0 to TC2
Full config:
  REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
  REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

  REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC0_RC2   = F_CPU / 128 / 1;
  REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
  REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

  REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC2_RC2   = F_CPU / 128 / 10;
  REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
  REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;


How to upload a sketch to an atmega328 via FTDI FT232RL UART and Arduino IDE?

Answering my own question; I just got lost in the troubleshooting.

Though I tested it both ways, I evidently overlapped issues, masking the core problem. Upload using programmer works great for transferring your sketch but it does NOT allow sketches to be uploaded via serial later. (Not sure if there is an inherent or logical reason for this, but this is what I have found by experimentation).
And like hcheung mentioned in the comments, a capacitor on the FTDI reset line is required. Connecting it directly will NOT work. I used a 0.1uF and it worked well. I have attached a couple different photos of my setup for someone following this path in the future. Note that the LED I am using has an internal resistor; a normal LED will need an 1k series resistor. Also, leaving the ISP programmer attached while uploading a sketch over serial did not seem to cause any issues.


i powered it with a 12v source and i got 12v out on Vin but 0 on 5V
  and 3V.

The fuse or the Vin input diode or the 5V voltage regulator or all of them could be damaged.

  i plugged it into my pc. The power led and the 13 pin led were on but
  my pc couldn't recognize my device.  In arduino ide i couldn't find
  the port and the tx and rx leds didn't blink at all.

The MCU could be damaged.
The USB chip is dead (Because there is no rx blinking during programming).

If you connect the arduino through USB and there was not 3.3v at the 3.3v supply rail, the 3.3v voltage regulator is dead.

You had better buy a new one or if you want to fix it to gain experience go for it.


From https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/

  analogRead()

  Reads the value from the specified analog pin. The Arduino board
  contains a 6 channel (8 channels on the Mini and Nano, 16 on the
  Mega), 10-bit analog to digital converter. This means that it will map
  input voltages between 0 and 5 volts into integer values between 0 and
  1023. This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit.

It is likely what you are seeing is noise and is to be expected. The source of the noise is likely multiple and could be environmental physical metallic or magnetic objects some distance away that are moving, electrical wiring (mains) nearby, and noise introduced by the power supply to the Arduino.

If you want to get a stable precise reading that close to the minimum step size, you will want to take several readings and average them. The more you read and average, the more you can eliminate the random effect of the noise, but the tradeoff is that it is slower because you are taking tens or hundreds of readings just for one result.


How are errors (not related to syntax) managed in arduino and in the AVR architecture in general?

The simple answer is: they are not handled at all.

According to the C and C++ standards, what you are invoking is called
undefined behavior, meaning anything can happen. In practical
terms, it means that the compiler can do its optimizations assuming
you will never invoke undefined behavior, and completely disregard what
could happen if the assumption does not hold. The generated code could
be completely broken, it won't be the compiler's fault.

The AVR architecture cannot do divisions, nor floating point math. Thus
all the errors you have here happen at the software level. Note that
sqrt(-10) is not an error (it's NaN, which is correctly handled by
the avr-libc), but converting that to an int (which you do when you
assign it to result) is an error.

If you really want to know the details of what happens with each of
these errors, there is only one option: you have to disassemble the
executable program and read the assembly listing.


No, you can't "share" pins between shields, except in specific circumstances (open-drain interrupts, I2C or SPI buses, etc).  General GPIO pins connect to just one device at a time.

I can't tell from that picture, but it is highly unlikely that all 8 of the IO pins are actually in use by the shield, and the ones that aren't actually connected to anything within the shield are available for another shield placed on top to use.  You'll have to look at the schematic or manual for the shield to know exactly which pins are used for what and which are available for other shields to use.

However, one thing to note with that shield - it doesn't appear to pass through the power header, so how a shield on top would get powered at all is a mystery to me.


How many connections can Arduino I2C method create?

The limiting factor is the bus capacitance. This is the limit of the total capacitance of the bus from all devices connected to it plus the capacitance of the wires used.
It is also affected by the value of the pullup resistors.
The limit, according to the specifications, is 400pF.  An Arduino has an input capacitance of 10pF.  So ignoring the wires that's an absolute limit of 40 Arduinos all connected together.
Reduce that a bit for the wires, so say 30 is a reasonable estimate. Then reduce that again if you're using the internal pullups which are about 10x bigger than they should be. That gives you a guestimate of 5-10 devices.
Use proper pullups instead of the internal ones (why oh why oh why did Arduino ever encourage and even make default such a stupid option?!?!?!) of say 1kΩ and keep wires very short and you'll probably be OK up to 20-25 devices.


Try using this code, I have edited some parts of your code so this should work.

#include <LiquidCrystal.h>

const int rs = 30, en = 31, d4 = 32, d5 = 33, d6 = 46, d7 = 47;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup()
{

  pinMode(36, OUTPUT);
  digitalWrite(36, LOW);
  delay(5000);    //Its okay to use delay here since its in the setup() function and will run only once

  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);

  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop()
{
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

For this Hello World sketch, avoid using delay(); statement in the void loop() as it is not good to use when you have the millis(); used.

If the above wont work, check your LCD Wiring, many problems usually arouse from wrong wirings.
Also I may suggest you to use some cheap LCD I2C Backpacks as this will ease the coding and will use less wire and pins on your Arduino. Here is a example

If your'e going to use a I2C LCD Backpack, here is a working sample code.

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

#define BACKLIGHT_PIN     13

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

// Creat a set of new characters
const uint8_t charBitmap[][8] = {
   { 0xc, 0x12, 0x12, 0xc, 0, 0, 0, 0 },
   { 0x6, 0x9, 0x9, 0x6, 0, 0, 0, 0 },
   { 0x0, 0x6, 0x9, 0x9, 0x6, 0, 0, 0x0 },
   { 0x0, 0xc, 0x12, 0x12, 0xc, 0, 0, 0x0 },
   { 0x0, 0x0, 0xc, 0x12, 0x12, 0xc, 0, 0x0 },
   { 0x0, 0x0, 0x6, 0x9, 0x9, 0x6, 0, 0x0 },
   { 0x0, 0x0, 0x0, 0x6, 0x9, 0x9, 0x6, 0x0 },
   { 0x0, 0x0, 0x0, 0xc, 0x12, 0x12, 0xc, 0x0 }

};

void setup()
{
   int charBitmapSize = (sizeof(charBitmap ) / sizeof (charBitmap[0]));

  // Switch on the backlight
  pinMode ( BACKLIGHT_PIN, OUTPUT );
  digitalWrite ( BACKLIGHT_PIN, HIGH );

  //lcd.begin(16,2);
  lcd.begin(20,4); // initialize the lcd

   for ( int i = 0; i < charBitmapSize; i++ )
   {
      lcd.createChar ( i, (uint8_t *)charBitmap[i] );
   }

  lcd.home ();                   // go home
  lcd.print("LCD TESTER - BY:");
  lcd.setCursor ( 0, 1 );        // go to the next line
  lcd.print ("ABBAS (PRJCT.ME)");
  delay ( 3000 );
}

void loop()
{
   lcd.home ();
   // Do a little animation by writing to the same location
   //for ( int i = 0; i < 2; i++ )
    for ( int i = 0; i < 4; i++ )
   {
      //for ( int j = 0; j < 16; j++ )
      for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 1 );
       for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 2 );
       for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 3 );

   }
   delay (200);
}


Try moving dht.begin(); to setup().

The DHTs are pretty slow and need some time (of the order of seconds!) between consecutive reads. In dht.begin() an internal timer is reset that is used in readTemperature() to ensure that reading data from the DHT is not attempted in shorter intervals than supported. By calling dht.begin() every 300 ms you're making this meachanism inoperative. You're supposed to call dht.begin() only once at start-up.

Edit: And please also remove the Timer1 that calls loop. loop is already an infinite loop, so no good in calling it additionally from an interrupt...


Protecting variables and functions within a library that has no class

If your library is implemented in a single .cpp file, you can define these
variables and functions within that file, and give them the static
qualifier:

static int my_private_variable = 42;

static void my_private_function()
{
    ...
}

Obviously, there should be no mention of them in the .h file.

Note also that we are talking about global variables. Local variables
are already hidden within the defining function.


Why did my pushbutton LED circuit work when my wiring was wrong?

The LED wired to the push button was turned ON by the push button closing the circuit, without any intervention from the micro controller.
That's a pretty simple circuit: a voltage source, a switch, an LED and a resistor, all in series. When you close the circuit the LED turns on. Simple.

The code on your microcontroller is watching the state change on the button and turning ON/OFF the on board LED: it has nothing to do with the LED in your circuit/breadboard.


Start by correcting the obvious:

const int btn1 = 2;
const int btn2 = 3;
const int led = 13;

void setup()
{
  pinMode(btn1, INPUT_PULLUP);
  pinMode(btn2, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
}

void loop()
{
  if (digitalRead(btn2) == LOW) {
    blink_slow();
  }
  else if (digitalRead(btn3) == LOW) {
    blink_fast();
  }

void blink_slow()
{
  digitalWrite(led, LOW);
  delay(1000)
  digitalWrite(led, HIGH);
  delay(1000)
}

void blink_fast()
{
  digitalWrite(led, LOW);
  delay(500)
  digitalWrite(led, HIGH);
  delay(500)
}

The mistakes where 1) const variable assignment, 2) using pin 1 (TX) is a potential risk if you later what to use Serial for debugging, etc, 3) condition expression, and a lot of formatting. Open your C/C++ book and check the syntax.

Now your turn to improve this!


Is it right to connect Serial module directly?

Maybe the serial module has a serial cable attached to it which gives a voltage.

I think it can hurt, since you have two voltage sources, one from the Arduino and one from the Serial cable. Not using the power wire from the serial cable should fix the problem.

A resistor will not help because you still have two power sources in case you have both voltage from the Arduino (adapter/USB) and serial.


A wiring diagram would help! But it sounds like you're powering your sensor from the Arduino's AREF pin. That is not the purpose of AREF; AREF is there for you to provide an accurate +5v or other reference voltage to the A/D convertor.
You need to power the sensor independently from your 5v supply (and not through the Arduino either, because of the sensors current draw); connect the sensor's Analog Out to one of the Arduino's A/D pins, sensor Ground to the supply ground. The digital out appears to be optional, if all you want is a go/no-go output that you adjust with the on-sensor potentiometer.


Make a PC graphical interface for Arduino - Any easy software?

The "best" software for me is the free Visual Studio Express for Desktops.

Using C#, I would add a SerialPort component to the form, configure it for the same COM port as the Arduino/FTDI, then send commands to it.

Visual Studio is "stupid simple" (I'm not implying anything :D). Double-click Button in the toolbox(1) and it creates one. Double click the button(2), and it outlines the code and attaches the Click event to it for you. Double click Components>SerialPort(3) to create one. My code is highlighted in blue to the right and this took all of 1 minute to create.

To point you in the right direction on the Arduino side, here is the structure of the "command" I sent in the screenshot:

XXXYYYZZ
Where:
XXX = 000b for "turn off", 001b for "turn on", 010b for "toggle", 011b for "read pin"
YYY = Pin number //Max = 111b = 7 (+ 0) = 8 uniquely addressable pins (using 3 bits)
//Pin number does not have to match the MCU port/pin designations
//MCU will convert logical pin #'s 0-7 into the correct physical port+pin
//For more pins, steal another bit from ZZ; Max for YYYY = 1111b = 15
ZZ = Spare bits //Tell the Arduino whether to acknowledge or not, etc.

00100100b = "Set pin 1 high"
01001000b = "Toggle pin 2"
10000000b + 0xAA (two byte command) = "Reply with contents of register 0xAA"

Additional commands can be created to tell the Arduino to reply with a specific variable or status.

bool isRegisterRead = false;
bool isMultiByte = false;
while (true)
 if (wasByteReceived) //This flag is set in the RX interrupt and the byte is saved to byteReceived
  if (isMultiByte) //Second byte received
  {
    if (isRegisterRead)
    {
      //We need to read and send the value of the register at the address in byteReceived
      ReadAndSendRegisterValueAtAddress(byteReceived);
      isRegisterRead = false;
    }
    else DoSomethingWith(byteReceived);
    isMultiByte = false; //Start over
  }
  else //First or only byte received
  {
    //Consider using a ZZ bit to indicate more data instead of listing them explicitly
    if (byteReceived == 0x80) //A multi-byte "read register" command
    {
      isMultiByte = true; //Next byte received is money
      //For my example we need to set a flag somewhere to indicate that we are reading a register
      //isRegisterRead should be set to true by DoSomethingWith
    }
    //Is there any processing for the "command" byte? (i.e. extract and save the pin number)
    DoSomethingWith(byteReceived); //Process one-byte command or first of two-byte command
  }


Cannot spin motor 28BYJ-48 with controller board ULN2003APG

What happens if you change

pinMode(pin1, INPUT);
pinMode(pin1, INPUT); // Pin 2 ?
pinMode(pin3, INPUT);
pinMode(pin4, INPUT);

to

pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);

Answer for Q1 - Q3. You are using pinMode as an input. Using digitalWrite() on an INPUT will enable (HIGH) or disable (LOW) the internal pullup resistor on the input pin. The pin will not be able to "source" enough current to operate the stepper motor.

A4. The stepper motor has a "mechanical" 1/64 gear ratio. This is why it is hard to turn by hand.

Here are 2 pages that will help you to understand the issue: https://www.arduino.cc/en/Reference/PinMode and https://www.arduino.cc/en/Reference/DigitalWrite.


Linear Regulator Dropouts
The linear voltage regulators found on that board are going to expect more than 5V at the barrel jack, because they require a minimum "drop out" voltage.  The AMS1117 that is on that board, so far as I can tell, has a drop out voltage up to 1.3V.  So you would want at least 6.3V (perhaps better 7V) at the barrel jack in order to get 5V out of it.
So the NodeMCU board may be seeing 5 - 1.3 or 3.7V at the input to its 3.3V regulator, which also requires its own drop out.  The output of that 3.3V regulator may then be significantly below what the esp8266 specified operating voltage range.
UPDATE
So I did the tests mentioned in the comments, just to illustrate the problem.  And the results are about as expected.
I altered the stock blink sketch that comes with IDE version 1.8.13 to use LED_BUILTIN (as opposed to 9) in the pinMode and digitalWrite calls.
I changed the LOW period, which is LED ON for my board, to 10000ms so that my voltmeter would have time to settle on a voltage test across the LED.
And I uploaded to the board, a NodeMCU 1.0 clone by Hitletgo.
When powered on its USB micro b jack, 3.3V labeled pin of the broad measuring 3.30 V.  The LED color is blue, it is bright and it is dropping 2.66V.
Then I switched to powering the NodeMCU board by via of VIN pins from the YwRobot regulator board.  I provided 5.05V to the barrel jack.  To not great surprise, it does not blink.
The voltage out of regulator board was 3.26V.  To be clear, I have this jumper for 5V.  As a sanity check, I jumpered it for 3.3V and got about 2.5V out of it.  Again, this is unsurprising because it also needs a dropout voltage.
I then measured the "3.3V" header line on the NodeMCU itself to be 2.14 V.  Without sufficient voltage into the 3.3V regulator, it is not providing 3.3V out.  And what it is producing is below that LED forward voltage when lit.  So it is not surprising that it is not lit.
The ESP8266 technical specifications suggest that it can run down to 1.8V.  So just for the hell of it I connected the board back to USB and updated the blink sketch to "blink" D8 (or GPIO15) 4 seconds on, 4 seconds off.  I did not attach anything to this pin except the voltmeter.
I then reconnected the board to the test rig and found with a meter that it is "blinking" D8 just fine with a logic level consistent with the voltage the ESP8266 is actually receiving.
So in summary, the arrangement here is running the ESP8266 but there is not enough available voltage for it to light the LED.  And it is very likely the exact same thing is happening for you.


Controlling mains (230 V) supply up to 5/10 amps using Arduino

The PowerSwitch Tail 2 is a great way for experimenters to control mains voltages. It is insulated and internally decoupled, so you only have to hook up 5v, gnd, and a signal line to control it.

This model supports only 120V, but there are also kits for 230V.

image from sparkfun


Trying to flash ESP8266 with Arduino UNO

You do not need the level shifter. The input pins of the ESP8266 contain over-voltage (though not over-current) protection. All you need to do is limit the current that can flow through the over-voltage protection circuit, and all that needs is a series resistor in the region of 100Ω or so.

And the Arduino already has that protection between the ATMega16U2 and the TX/RX pins anyway in the form of 100Ω resistors that it uses to prevent short circuits between the two MCUs on the board, so you don't need to add it in this instance (you do if you want to communicate between the ATMega328P and the ESP8266, but only between the Arduino's TX and the ESP8266's RX pins).

When it comes to actively running the ESP8266 it can be beneficial to power it from a more powerful 3.3V regulator than the 150mA one on the Arduino since when transmitting the ESP8266 wants more than that, but for simple flashing of it the Arduino's 150mA regulator should do the job fine.

One thing to note though: I don't like the look of the soldering on your ESP8266 pins. I would be inclined to re-solder those joints. Add a bit of flux to help the solder flow properly.


As jsotola writes, you are running through the 0-89 position and updating leftDistance every time. Then you find the middleDistance and finally you go through 91-180 and update rightDistance. After the two for loops, leftDistance will have the value for 89 and rightDistance will have the value for 180 because you overwrite your value without doing anything with it.
Start by skipping the for loops and measure at 0, 90 and 180 and use these values as you left, middle and right distance. When deciding if you want to back up, use the middle distance. Remember to use a delay between measurements that is large enough for the servo to get to the position for the next measurement


How to package a 16 bit integer to send it with serial.write?

You need to send the uint16_t as the two the individual bytes it is composed of, one at a time, in whatever order your Arduino code and the code on the PC agree on: (MSB first, aka, big-endian; or LSB first, aka little-endian).

Since it would be possible for the two devices to get out of sync, you may also want to package up the two bytes with a third, or "start-byte". Pick some fixed value (such as 0xCC) that has a couple of its MSbits set, then the MSB, then the LSB. Your receiver can know to look for that fixed value, then the MSB (which it knows can't have those high bits set because the analog data is only 10-bits), then the LSB (which could have any value).

The PC should only accept a three-byte packet when it has received one that fits that scheme. Otherwise it waits for another 0xCC (or whatever value you choose), collects two more bytes, and tries again.


Can I make delayMicroseconds more accurate?

As explained in the previous answers, your actual problem is not the
accuracy of delayMicroseconds(), but rather the resolution of
micros().

However, to answer your actual question, there is a more accurate
alternative to delayMicroseconds(): the function _delay_us() from
the AVR-libc is cycle-accurate and, for example

_delay_us(1.125);

does exactly what it says. The main caveat is that the argument has to
be a compile-time constant. You have to #include <util/delay.h> in
order to have access to this function.

Note also that you have to block the interrupts if you want any kind of
accurate delay.

Edit: As an example, if I were to generate a 4 µs pulse on PD2
(pin 19 on the Mega), I would proceed as follows. First, notice that the
following code

noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

makes a 0.125 µs long pulse (2 CPU cycles), because that's the
time it takes to execute the instruction that sets the port LOW. Then,
just add the missing time in a delay:

noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
_delay_us(3.875);
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

and you have a cycle-accurate pulse width. It is worth noting that this
cannot be achieved with digitalWrite(), as a call to this function
takes about 5 µs.


https://blog.adafruit.com/2010/06/11/aprs-radio-shield-for-arduino/
Be warned you need a license to transmit on amateur frequencies at least in the US, you will also need to hook up a transmitter for this shield.

GSMShield would also be great and is something I'm thinking about using for my project, the way the Arduino IDE is setup and the libraries already in place I'm sure it would be easy to turn text messages into commands or readable and usable data between the sender and receiver.

Here are two ways one using a long range radio frequency or the GSM network. We would need to know more exact data of your project on how to implement these two solutions to accomplish what you would like to do.

The first option is most likely going to be the lesser option if you don't have a license to transmit long range frequencies and do not have experience.

The second option is easy and all you would have to do is make sure both sender and receiver are within a GSM network.

Good luck and I'm excited to see what other solutions others may post since I'm in the same boat.


The SD card is a 3.3 V device. The 5 V module with SD card adapter steps down the voltage for powering the card and has logic level conversion for card's SPI pins.

If you want to connect SD card to a 3.3 V board it is better to use a simple breakout board without power and signal conversion.

I do not recommend you to connect a 5 V SPI device to MKR SPI pins without logic level conversion.

EDIT: smajli analyzed in his answer the logic level conversion chip used on the adapter you use. it doesn't output more than 3.3 V and you can use it powered from 5 V. but it is still a workaround.


The concatenation is working fine in both instances.

What is wrong, though, is that you can't return a pointer to a locally declared array from a function. That array no longer exists when you leave the function.

The thing to remember with arrays is that you never pass the actual array to or from a function. All you pass is a pointer to the memory address where the array is.  If you allocate an array in a function that memory is allocated on the stack. When you return the array from the function you return an address that is (currently) within the stack.  When you leave the function all memory allocated on the stack by that function is removed, and that includes your array.

There are four ways of solving the problem - all of them have their pitfalls.

Use a global "scratch pad" array that is big enough for any concatenating you may want to do. Do your concatenation in there.
Declare your array static, which means it's allocated only once and can be returned from the function - but like the global one you have to have a fixed size.
Pass a pointer to a suitably sized array to your function to have that array used for the concatenation, and
Allocate memory on the heap using malloc().

My normal method is number 3. It's the safest and most flexible:

const char *a = "part a";
const char *b = " part b";

char all[14];
doConcat(a, b, all);

void doConcat(const char *a, const char *b, char *out) {
    strcpy(out, a);
    strcat(out, b);
}


Elegant solution for refreshing TFT display content?

If you look in the "Adafruit_GFX.cpp" you will see the following.

void Adafruit_GFX::setTextColor(uint16_t c) {
 // For 'transparent' background, we'll set the bg
 // to the same as fg instead of using a flag
 textcolor = textbgcolor = c;
}

void Adafruit_GFX::setTextColor(uint16_t c, uint16_t b) {
 textcolor   = c;
 textbgcolor = b;
}

If you only want to Draw the Character with a transparent background meaning you only write the character setTextColor in the prescribed pixels changing none of the surrounding pixels in the character block defined by x, y, setTextSize.

TFT.setTextColor(GREEN); //With Transparent Text Background not updating surrounding pixels.

If you want to Draw the Character with your background color, replace app pixels in the character block defined by x, y, setTextSize with your chosen text color and your background to be the same as your chosen background. This will overwrite all pixels with old character that are no longer used with the background color all at the same time preventing mess of pixels, and character flashing.

TFT.setTextColor(GREEN, BLACK); //With Text Background Color updating surrounding pixels.


The Pro Mini has a 3.3 volts regulator rated to 150mA, as you can see here https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf, it´s rated to work from 16V but by personal experience a 5V~5.1V 200mA power supply is the best option to power it without burning it, even if it burns, you can search at the internet something like

"Desoldering led and voltage regulator on Arduino Pro Mini"

Regards


You mustn't terminate a #define with a ;.  Semicolons are for C and C++ statements. #define is a preprocessor statement.

#define creates a literal string replacement, so when you use it you end up with:

const char keymap[5;][6;] = {...

which is, of course, wrong.


Weird sound when modulating the pulse width on Arduino

Seems like you are using the system clock micros() to  calculate elapsedTimeMicros, so probably the time spent on the process of calculation and sending signal to the pin may affect it, which may lead to inconsistent duty cycle.


Converting the 3.3V PWM signal to 5V PWM signal

Looking at TB6612FNG datasheet i read

  Logic supply voltage (VCC) can be in the range of 2.7--5.5VDC

So, if you supply 3.3V to VCC all should be ok, if the motors themselves get enough power (via VM)


Arduino Uno simple LED example with pointers

You made two small mistakes:

The addresses of the I/O registers are 0x24 for DDRB and 0x25
for PORTB. The numbers you used are I/O port numbers, but since
pointers are supposed to point to memory, you have to use the
memory-mapped addresses instead.
Pin 13 is PB5, not PB6.

With these two mistakes fixed, your code works as expected. There are
still two issues however:

Under some circumstances, the compiler can optimize away some writes
to these registers. You have to qualify the pointers as “pointer to
volatile data” in order to avoid this. Even if your simple example
does not show this problem, it is always safer to use the qualifier.
The compiler generates inefficient code. Not as inefficient as
digitalWrite(), but still... It knows how to optimize, but it is
prevented to do so by the fact that your pointers are modifiable. You
should qualify them as const if you want to benefit from compiler
optimizations.

With those fixes, your pointer definitions would look like:

volatile uint8_t * const data = (uint8_t *) 0x25;
volatile uint8_t * const dir  = (uint8_t *) 0x24;

and access to them gets compiled into efficient in ans out assembly
instructions.

That being said, if you want to do direct port access, I would recommend
doing it the avr-libc way:

void setup() {
    DDRB  = _BV(PB5);
    PORTB = _BV(PB5);
}

void loop() {
    PORTB = _BV(PB5);
}

The way the AVR-libc defines the I/O registers is roughly equivalent to

#define PORTB (* (volatile uint8_t *) 0x25)


Arduino Serial.write sending more than 64 bytes

Here's the problem:

  sendEncoderData() is called by an interrupt service routine.

There is an internal 64 byte serial transmit buffer that is filled by Serial.write().  That buffer is empted by sending the data a byte at a time using an interrupt.

If you are in an interrupt (at a higher priority than the serial interrupt) then the interrupt that sends the data can never happen, so the buffer just fills up and stops when it gets to 64 bytes.  It will hang until there is room for more bytes in the buffer, and that will never happen because you're not allowing the data to be sent.

The answer (as I and others have said many times in the past): Never use Serial in an interrupt.


Compiling error:passing as 'this' argument

If you want to use an instantiated object as volatile then the functions within it also have to be marked as volatile. That tells the compiler that the instance pointer you will be passing to the function (the auto-inserted this parameter) is volatile:

class Timer{
  private:
    uint32_t start_time;
  public:
    Timer(){
      start_time=millis();
    }
    void mark() volatile {
      start_time=millis();
    }
    uint32_t lapsed() volatile {
      return millis()-start_time;
    }
};


I'm using an Arduino and DS1307 for creating RTC but my code has some issue

Lets start with the order of the registers:

seconds  -- bit 7 is clock start/stop bit, 0 = enabled
minutes
hours    -- bit 6 is selector 12/24 hour,
         -- when in 12 hour, bit 5 is am/pm, 1=pm
         -- When in 24 hour, bit 5 indicates in hour 20...23
day      -- week day 1...7
date     -- day of month 1...31
         -- where the most significant nibble can contain the values
         -- 0, 1, 2, 3
         -- where the least significant nibble can contain the values
         -- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
month    -- 0x1x indicates in upper 10 months
year
control
<other ram>

When writing these registers, the prior time is transferred to a background/image of the main registers.

Of key importance is the 'ack' bit, which is 'echoed' at the end of each byte transferred.  Here are the details:

DS13077 of 12Acknowledge: Each  receiving  device,  when  addressed,  is  obliged  to  generate  an  acknowledge  after  the reception  of  each  byte.    The  master  device  must  generate  an  extra  clock  pulse  which  is  associated  with this acknowledge bit.A device that acknowledges must pull down the SDA line during the acknowledge clock pulse in such away that the SDA line is stable LOW during the HIGH period of the acknowledge related clock pulse.  Of course, setup and hold times must be taken into account.  A master must signal an end of data to the slave by not generating an acknowledge bit on the last byte that has been clocked out of the slave.  In this case,the slave must leave the data line HIGH to enable the master to generate the STOP condition

so the first problem I see is the code sequence does not match the register sequence.  This is an error.

the second problem I see is the ACK bit is being set to the wrong value


Communication with two XBee's and Arduinos over serial

Did you set one of your modules into coordinator mode?
Every xBee network needs a coordinator. Therefore, you need to put one of your Xbee modules into coordinator mode using the "Function Set" dropdown box in X-CTU. The coordinator has the fixed address 0, so you need to set DL and HL address parts of the other module to 0. On your coordinator, you can set DL to FFFF and HL to 0, which is the broadcast address.

Softserial won't help you. It's just a way to use some of the pins as an additional serial port. Don't use that if you can use a hardware serial port.


How to convert char[] to int with fail\success control?

It isn't doable, reliably, with the given specs. If the array has garbage in it, it won't necessarily fail to parse as an int. That said, you can try to parse as an int with atoi() or sscanf(), as suggested in the comments, and report that it did or did not parse, but not necessarily whether it is valid in some respect.

If you're in control of the array, zero its first element. Then if you get back a non-empty string, at least you'll know some command parameter had been placed in it.


What will happen is you will damage your LED and/or your Arduino since you haven't mentioned a current-limiting resistor (220 ohms could well be suitable).

However the general concept is perfectly sound. You could, for example, have two LEDs, wired in opposite directions. By bringing one pin LOW and the other HIGH, one LED would light up, and by reversing the output to the pins the other LED would light up. If both pins were either HIGH or LOW then neither LED would light up, as there would be no voltage difference between the leads.

There is a calculator for LED resistors.


Why can't most servos rotate more than around 180°

Fundamentally, because the systems they were designed for convert rotary motion to linear, typically with a range substantially less than 180 degrees (probably more like 120 degrees).

Next, because the control scheme of PWM position pulses is not able to convey requests over an arbitrary range - the mapping of pulse width to position must be limited, and it is sensibly set up to map to something related to the useful range.

Because these limitations in task, a fairly ordinary rotary potentiometer of less than 360 degree range can be employed for position sensing.

Given that the useful range is limited, and the potentiometer relatively easy to damage by over rotation, the gearbox is typically constructed with a mechanical rotation stop somewhere outside the normal range of self rotation.


Looking at the datasheet the output is +/- 4 volts, so this is not suitable to connect directly to the Arduino, because the input pin will not tolerate -4 V.

I am no Hall Effect sensor expert, but a quick search on Google showed another potential problem: If you are planning to measure AC current, and you try to sample the output on the Arduino, the reading will average out to zero (half of the time positive, half of the time negative).

What may help - and this is a bit of a guess - is to put a diode in series with the sensor output, oriented so that you only get the positive pulses. That is, the anode connected to the Hall Effect sensor, and the cathode (with the black line) on the Arduino side.

Then you probably want to smooth the voltage so you can read the average voltage with the ADC converter, rather than what it is at a particular millisecond. A low-pass filter will take an average, which you can then read with analogRead.

Something like this:

I made up that circuit driven by a signal generator (8 V peak to peak, i.e. +/- 4 V) and found a 400 mV drop over the diode using a 1N4148 normal diode, and a 160 mV drop using a BAT85 Schottky diode.

With a 3 V peak-to-peak signal the voltage drop with the Schottky diode reduced to 120 mV, so it wasn't totally linear.

As Majenko pointed out, there is a voltage drop over the diode. You can make a Precision Rectifier out of an op-amp and a few other parts, like this:

This avoids the problem of the voltage drop (put this in place of the diode in the earlier circuit).

If the signal is AC then the smoothing circuit I described above will only give you an average voltage, not a peak one. You may want to sample rapidly in order to find the peak values.


Connecting a motor to Arduino UNO Play breadboard

Using same Voltage supply to power Arduino Board and motor simultaneously is usually not a good practice.

So, what you can do is use separate batteries to power Arduino and motor as shown in image below

However you can also power arduino and motor from single power supply, but in this case you should first think of current ratting of your battery and current consumption of your Arduino (normally 500mA) and motor. As shown below,

Hope it help. Any question Comment below.


Yes, you can.  That's the purpose of the SoftwareSerial - to allow you to complement the hardware TX/RX with other pins defined by software.

One thing to note with SoftwareSerial - it's half duplex. It can either send or receive, it can't receive while it's sending.


Read Serial data from an arduino with c code

RS232 uses +/- 12V (or sometimes +/- 5V), and is not compatible with TTL Serial, which uses 0V/5V. Also +12V in RS232 represents 0 and -12V represents 1; inverted from normal TTL.


How to add this old BASIC code snippet to work in Arduino C++ for FastLED?

Fairly simple. Understand what the basic code is trying to do and recreate that functionality in c.

In this case, it is looking for a set of conditions to trigger the generation of three random numbers which are then combined into a code for the run array.


This is more a wild guess than a real answer... Assuming your terminal
is using a character set more or less like ISO-8859-1 or Windows-1252,
then you are receiving 0xA4 when you expect 0x48. My guess is that the
very first start bit got lost somehow.

Here are the serial port waveforms corresponding to the expected and
received bytes. ‘S’ and ‘T’ are the start bit and stop bit respectively.
The data bits are sent least-significant first. The idle state is HIGH:

• ‘H’ = 0x48 = 0b01001000

────┐               ┌───┐       ┌───┐   ┌──────
    │ S   0   0   0 │ 1 │ 0   0 │ 1 │ 0 │ T
    └───────────────┘   └───────┘   └───┘

• ‘¤’ = 0xA4 = 0b10100100

────┐           ┌───┐       ┌───┐   ┌──────────
    │ S   0   0 │ 1 │ 0   0 │ 1 │ 0 │ 1   T
    └───────────┘   └───────┘   └───┘

You can see that, if you remove the start bit from the first waveform,
you get exactly the second one. I do not know what may be the cause of
this though.


You have a big 5s delay in your code, right after both serial commands. You don't need a delay there; it does not do anything. But it makes your code unresponsive. So you can simply remove it.
I guess you wanted to do some timed thing there and accidentally left it there.  But in general you should not use any big delay() in any code. As you have seen, it makes your code unresponsive, as the Arduino doesn't do anything during this time. Instead look at the BlinkWithoutDelay example, that comes with the Arduino IDE (Its a really important principle to learn). It uses the millis() function (or alternatively the micros() function) to check, if it is time to do something. If yes, it will execute this, if not, it will exit fast and give the rest of the code an opportunity to execute. Much like you would bake a pizza: You start the baking and then regularly  check the clock, if it is time to take the pizza out. In between you can do other things, like reacting go messages on your phone. Its the same principle, just in code.


What is the purpose of Serial.println() without an argument?

To complement jose can u c's answer: the Arduino Serial object uses
CRLF as the end-of-line marker. That's an ASCII CR (carriage return,
or '\r' in C) followed by ASCII LF (line feed, '\n' in C). Thus,

Serial.println();

is equivalent to

Serial.print("\r\n");


Your issue is a C programming issue and has nothing to do with the Arduino specifically.  You should research how to implement a circular buffer.  You don't want to move around the values within the array, but rather just increment array index values.  Keep two index values, one of the current index position (the place where the next recorded value will be placed) and another of the number of values recorded.  Eventually the number of values recorded will be equal to your maximum array size and only the index position will increment.  When the array index exceeds the maximum array size it wraps back to 0.


Is there a way to make the RESET pin work in the inverse?

My personal preference would be to attach a NOT gate to the RESET pin.  This can be constructed very simply from a single NPN transistor (or N-channel MOSFET) and a resistor.

simulate this circuit – Schematic created using CircuitLab
With the wire disconnected R1 turns on Q1 which pulls the RESET pin LOW.  With the wire connected Q1 is turned off, allowing RESET to be pulled back up by the pullup resistor that's built into the Arduino.
This method also won't interfere with the programming reset action of the Arduino.


The way to do this is:
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);

if (isnan(h) || isnan(t) || isnan(f)) {
  Serial.println("Failed to read from DHT sensor!");
  return;
}

See https://www.hackster.io/MisterBotBreak/how-to-use-temperature-and-humidity-dht-sensors-9e5975 and https://stackoverflow.com/questions/40874880/getting-nan-readings-from-dht-11-sensor.
NULL should only be used with pointers.


Arduino is running as a server, but want to occasionally act as a client to update time

There is no problem with running multiple servers and use multiple clients with the WiFi library of the ESP32 core for Arduino as it is not a problem with most of the WiFi libraries for Arduino (some can't run servers (TinyGsm) or can run only one server (WiFiEsp(AT)).

But you don't need a WiFiClient for NTP time. First because NTP runs on UDP and second because the ESP32 SDK provides SNTP and the ESP32 core for Arduino wraps it in functions presented in the ESP32 examples library's SimpleTime example.


Dc motor backvoltage, how to place the diode correctly?

I read when a motor stops then the backvoltage happens,

That is not true. With a brushed DC motor the back-EMF ("backvoltage") occurs at least twice (often more, depending on the number of commutator segments) per revolution of the motor.  Brushed DC motors are very noisy.

While you can use a diode (connected as you would for a relay) it's not the best solution.  Instead you really need a proper EMI-absorbing circuit.

This consists of three capacitors - all very small values, in the range 1-10nF, which connect all parts of the motor together and bleed off any induced voltages safely.

The first capacitor connects directly across the terminals.  This will safely remove the back-EMF created in the windings as the voltages switch back and forth due to the rotation of the commutator.

The other two capacitors each connect from one terminal to the metal housing of the motor (one to each side of the housing).  This will safely couple the housing to the rest of the circuit and cause it to act as a shield containing the magnetic fields better within the motor.


The pin is floating. Use pull up or pull down to help define its logic state.


Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega

easy.

find a copy of the datasheet for your mcu;
go to the section about your timer;
figure out a prescaler setting that yields the maximum roll-over count;
pick the timer mode that supports the roll-over count;
write your own analogWrite() function;
[optional] if you wish to reuse the stock analogWrite(), make sure that roll-over count calculated in 3) is a valid data type for the stock analogWrite(). If not, increase the prescaler in 3) until it is.
done.

edit: i decided to give it a try.

the following code:

void setup() {
  // put your setup code here, to run once:
  pwm1Set(TMR1_PS8x, F_CPU / F_PWM1 / 8);       //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  analogWrite(9, 20);                           //dc = 20/80=25%
  analogWrite(10, 40);                          //dc = 40/80=50%
}

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

produced the following output on an ATMega328p's TIMER1.

i'm reasonably sure that the output is indeed 25Khz.

the code itself however is capable of generating pwm at other frequencies.

edit2: the same code on mega2560 generating 25Khz pwm on pin6/7/8:

code used for that is as follows:

  //ps = 8x, top = F_CPU / F_PWM / 8 = 80
  //DC on Pin 6 = 20/80 = 25,
  //DC on Pin 7 = 40/80 = 50,
  //DC on Pin 8 = 60/80 = 75,
  pwm4Set(TMR4_PS8x, F_CPU / F_PWM4 / 8); analogWrite(6, 20);  analogWrite(7, 40);  analogWrite(8, 60);

pwm4Set() is a copy of pwm1Set(). Both are simple enough: only 5 lines of code used.


How to read Serial data when multiple functions are Running?

Then let scroll return immediately

void scroll() {
    static long timer = 0;
    static boolean scroll = true;
    if(scroll){
        dmd.clearScreen( true );
        dmd.selectFont(Arial_Black_16);
        dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
        scroll = false;
        timer = millis()
    }else {
        if ((millis() - timer) > 30)  {
            scroll = dmd.stepMarquee(-1, 0);
            timer = millis();
        }
    }
}

The static keyword means that the value of the variable will be kept across calls.

I used the fact that it will be called in a loop to remove the while loop inside. I split the function up into 2 parts: The reset and the update. We first run the reset to init the marquee. After the reset it will set the boolean so the next time it will enter the update part. Then I used the exit condition of the original loop to make it reenter the update part next time.


Quite possibly. The modern library format contains a list of board types it runs on (in library.properties). If the Due (SAM) isn't listed then it won't be included in the list of libraries.

For instance the SD library has:

name=SD
version=1.1.1
author=Arduino, SparkFun
maintainer=Arduino <info@arduino.cc>
sentence=Enables reading and writing on SD cards.
paragraph=Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card.
category=Data Storage
url=http://www.arduino.cc/en/Reference/SD
architectures=*

However the AVR specific SPI library has:

name=SPI
version=1.0
author=Arduino
maintainer=Arduino <info@arduino.cc>
sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus.
paragraph=SPI is a synchronous serial data protocol used by microcontrollers for communicating with one or more peripheral devices quickly over short distances. It uses three lines common to all devices (MISO, MOSI and SCK) and one specific for each device.
category=Communication
url=http://www.arduino.cc/en/Reference/SPI
architectures=avr

Note the last line of each - architectures=... - that defines what the library can work with. If your (unspecified) library doesn't have * or include sam in that parameter then there is no way that library will work with the Due.


"Serial" does not name a type -> How to solve this problem?

Your code would be a lot easier to read and find mistakes in if you formatted it. I see that you did that in the IDE, but in your question, you need to highlight all of the code, then click the "{}" button to make it look like code in your question.

When I pasted your code into my IDE and auto-formatted it, the answer was immediately clear: after the function microsecondsToCentimeters() you have written some code that is not inside any function. C and C++ don't allow that. The error message wasn't very helpful - the compilers easily get confused by our mistakes - but in this case, looking at the formatted code made it clear.

All of the executable code in a C or C++ program (Arduino IDE uses C++) must be inside a typed and named function. Since that is what the compiler was looking for, it seems to have interpreted the word "Serial" as a function type, but no type was defined with that name.

I'm not sure where you intended the lines from the end of long microsecondsToCentimeters() to go, but they need to be inside of a function, somewhere.


What overheads and other considerations are there when using a struct vs a class?

As taken from the accepted answer from When should you use a class vs a struct in C++?

  The only difference between a class and a struct in C++ is that
  structs have default public members and bases and classes have default
  private members and bases. Both classes and structs can have a mixture
  of public and private members, can use inheritance, and can have
  member functions.

  I would recommend using structs as plain-old-data structures without
  any class-like features, and using classes as aggregate data
  structures with private data and member functions.

Memory wise the access modifier makes no difference and given the memory constraints of the Arduino, people are less likely to use classes with complex hierarchies, but prefer the POD structs anyway.


Can I measure velocity from an accelerometer? How accurately?

The sensor in itself can't provide you the velocity. I have used it accelerometers in a couple of projects the easiest way to get the velocity is to constantly monitor acceleration changes and calculate velocity instantaneaously.

In order to do so follow these instruction. Pleas note that this is only 1 axis reading in actual case you will have to perform this for all three axis i.e. x,y and z.

I hope you are aware of the equation of motion (V = Vo + at)... The sensor will provide you value of acceleration at any given time. But acceleration can vary quite significantly during a huge time intervals so keep the time intervals 't' small. Lets say t = 10ms (depends on you). So calculate V after every 10ms intervale and this will give you current velocity at any given time. But what about Vo? As you know it is refered to as initial velocity so in the beginning it will be 0. Immediately after first reading when you are about to take second reading the Vo will change to the previous V calculated and hence forth.

This means Vo at any given interval is actually the V calculated in the previous interval.

I tried this method in my project when using accelerometer. hope it helps you as well.


Battery life calculation using Nano, NRF24L01+ and window magnetic reed switch

You should use interrupts for the reed switch and then put the microcontrolller into sleep for a keep alive interval. Your master device should check that the sensor is still active and set off the alarm if its not. You would also want to allow for a battery low condition that might disable the alarm for convince. This still should keep the power consumption low.

The nano is roughly 1mA @ 3.3v while the CPU is running and 72uA when its in sleep. Discounting power consumption in the alarm condition triggered by the interrupt using an interval of 9 seconds using delay or interrupt timers then average consumption then about a second to wake up and send a keep alive over the RF. (0.000072 * 9 + 0.001 * 1) / 10 = 0.0001648 amps. (average over 10 second duty cycle)

My guesstimate of your RF power consumption without knowing what kind of protocol would be somewhere around 128 bytes per transmission taking about 90ms. (0.0001 * 9910 + 0.015 * 90) / 10,000 = 0.0002341 amps.

Total of their averages is: 0.0003989 or 398.9uA.

Alkaline AA cells vary widely. So instead based on some Ni-MH with 2400mAh per cell and 1.2v

3 cells would be 3.6v so you'll "get" most of the mAhs out of the batteries.

2400mAh = 2400000uAh

2400000uAh / 398.9uA ~= 6016.54 hours or 250 days or 8 months.

Power consumption were intentional overestimates. You should be able to make it last a lot longer.

https://www.avrprogrammers.com/howto/atmega328-power
http://harizanov.com/2013/05/nrf24l01-power-consumption-footprint/


how to use hx-53 (IR Transmitter Infrared Sensor Module) with ESP32?

The HX-53 look like a IR LED and a current limiting resistor on a small PCB.

It also has a LED and a resistor in series for indication when the invisible IR diode is on or off.

So you can change the resistor to a lower value to match the 3,3 volt output from the ESP32.

Resistor values:

221 = 220 ohm   = IR LED
102 = 1000 ohm  = SMD indicator LED

So replace the 220 ohm with something near 75 ohm.

HX-53


Use of progmem in ESP8266 vs AVR and also how to handle large dynamic strings

On the ESP8266 flash is a very special case. Because the ESP8266 itself does not have any flash, but instead uses an external SPI-connected flash chip, accessing it is not an easy or technically obvious operation.

Reading from the flash chip is slow. Very very slow (by comparison to reading RAM).  Because of this where possible certain things are copied into RAM. Also, there are different sections of RAM that are dedicated to different purposes.

dram0 - This is your "Data" RAM. It's where your variables and such are stored (80kB total).
iram1 - Instruction RAM. It's here that interrupt routines need to be stored for rapid execution (32kB).
icache - Instruction cache. 16kB of data that is cached when reading from the flash chip. Executed code usually gets copied here.

Normally when you execute code the block of code that the instructions you are executing are copied from flash into the icache memory block and then executed. This is reasonably fast (reasonably in that there may be brief delays while copying the data from flash, but fast when actually executing. I don't know how efficient the cache is, whether it's split into different blocks that are loaded in the background by the memory controller as needed, but it seems to be a pretty efficient system that is used in practice).

Because of this disassociation of the CPU and flash string constants, unless specified otherwise, will be copied into dram0 during startup. This makes it very fast and simple to get at the data. Anything that you don't specify as PROGMEM will get copied into dram0. Note that you don't get all 80kB of the RAM to play with since the SDK uses a portion of it. You only get about 50kB at most (station mode - softap mode will use more).

Now... what does PROGMEM do on the ESP8266 then?  Well, it adds an attribute to the definition that tells the linker to place the data in a specific section in flash (.irom.text.<filename>.<line>.<number>). This prevents it being copied into dram0 at startup.

So how do you get at it? That's where the *_P variants of the string functions (and certain overloaded functions in the Arduino core) come into play.

The whole of the flash chip is mapped (or can be, depending on register settings) into the ESP8266's memory map (address 0x40200000). Which means that it's possible to get directly at the data. However since this access doesn't go through the icache RAM block it's slow. Very very slow. About 12x slower by some accounts. Also because data can be in different locations within the chip the addresses of your string data can't be directly hard coded. There has to be some form of "it's over there" redirection when reading the data (for example if you use OTA updates you get two distinct blocks of flash where your code can be stored - the currently executing code and the previously executing version). The *_P variants of the string functions take that into account and look up where in flash the current code is located before reading from it.

So to summarise: Not using PROGMEM gives you fast access to your string data at the cost of RAM, and limits the size of the data you can use. Using PROGMEM removes the size restriction, doesn't use RAM, but is considerably slower.

To specifically answer your questions:

The string data gets copied to RAM at startup.
The string data gets copied to RAM at startup.
The string data gets loaded from flash (using *_P variants of functions) when the String object is constructed (RAM is allocated on the heap at that moment in time). The RAM is freed when the String object is destroyed (goes out of scope).
The compiler has recently had an update that will deduplicate constant PROGMEM strings.
As mentioned above *_P copies directly from flash and is slow, but has no size limitation.


...Specify a programmer using the -c option and try again

For Arduino, the programmer switch must be -c arduino. The full arguments for avrdude, in the Atmel Studio 7 External Tools window, are:

-c arduino -p m328p -P COM3 -b 57600 -D -V -U flash:w:"$(TargetDir)$(TargetName).hex":a

See avrdude options.


Is this the right way of using an RF communication?

Credits for this answer are mainly for jsotola (see his remarks above). But I want to show an alternative to the if statements, and a way to get the last 4 bits:

In case you want to check for the least significant bits, use ((mySwitch.getReceivedValue() & 0xFFFFF0)
TO check for the least significant four bits (the data you want to act upon), use ((mySwitch.getReceivedValue() & 0xF)
Use a switch statement instead of the if statement; also in theory (I don't know the code of mySwitch.getReceivedValue() does not need to be executed multiple times.

So you get something like this:

void loop()
{
  unsigned long receivedValue = mySwitch.getReceivedValue(); // Call function only once

  if ((receivedValue & 0xFFFF0) == 0x6ED830)
  {
    // Process action
    switch (receivedValue & 0xF)
    {
    case 0x5:
      digitalWrite(13, LOW);
      break;

    case 0x8:
      digitalWrite(13, HIGH);
      break;

    case 0x6:
      mySwitch.resetAvailable();
      break;

    default: // All other values
      break; // Ignore
  }
}


I was just researching the exact question and I have some bad news.

The ORIGINAL nrf24l01+ alone use around 10-12 ma in transmitting, but unoriginal might even draw more. (https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf)

Nevertheless a standard CR2032 battery is simply not made to supply more than a few milliamps at the best, leaving your nrf24L01+ lacking enough current.

There is something called shockburst which can lower your consumption considerably at the cost of range - but if it will succeed in transmitting with one CR2032 I'm not sure about.

Edit:
If you add a capacitor you need to cover at least a 10ma drain for around 15ms (turn on - send - turn of immediately), that will require a minimum of a 200µF capacitor at 3V to be able to deliver the current while keeping above 2.0v.


You have control over when you place a byte in the TX buffer and control over when you read a byte from the RX buffer. You don't have control over when the master sends data to you, though, so somewhere is needed to store that incoming data until you read it. Since the master can start sending another byte before you have read the last one it's critical that the receiving shift register is separate from the register you read the shifted in data from.  Only when the complete byte has been shifted in does it get copied to the receive buffer, so that another shifting in can begin.

When transmitting you don't need to worry about that since what you write into the TX buffer is what is about to be shifted out. You don't write anything else until it's time to send the next byte, at which point the TX register is empty anyway.


Multiple variant.cpp entries for same physical pin

The analogWrite function checks the PIN_ATTR_ANALOG attribute from pin description in variant.cpp to determine if the pin has DAC capability. Then it checks if the pin is ADC_Channel0 or DAC_Channel0. This is unnecessary and redundant. There is no other use for DAC_Channel0.

In Arduino SAMD core and derived cores the pin 'map' in variant.cpp defines pin capabilities used by Arduino core. It is not a complete copy of the mux table from the datasheet. In some variant.cpp files comments contain the additional mux options of the pin.

For PWM the analogWrite function configures the pin and for SPI, the SPI library configures the pin.

If you want to use the pin for other SERCOM function, the function pinPeripheral is used to set up the pin. Here is a tutorial.

Arduino core doesn't support a configuration of a different wave output then analogWrite. To configure a different wave output or capture, a third party library or direct registers configuration is necessary.

The Arduino pinPeripheral(pin, peripheral) function uses the variant.cpp mapping and the possible parameters are:

PIO_EXTINT=0,     /* The pin is controlled by the associated signal of peripheral A. */
PIO_ANALOG,       /* The pin is controlled by the associated signal of peripheral B. */
PIO_SERCOM,       /* The pin is controlled by the associated signal of peripheral C. */
PIO_SERCOM_ALT,   /* The pin is controlled by the associated signal of peripheral D. */
PIO_TIMER,        /* The pin is controlled by the associated signal of peripheral E. */
PIO_TIMER_ALT,    /* The pin is controlled by the associated signal of peripheral F. */
PIO_COM,          /* The pin is controlled by the associated signal of peripheral G. */
PIO_AC_CLK,       /* The pin is controlled by the associated signal of peripheral H. */
PIO_DIGITAL,      /* The pin is controlled by PORT. */

If you are good with the Arduino variant.cpp configuration, then for direct registers access configuration the pin 'map' from variant.cpp and the pinPeripheral function can be at help if the pin should not be hardcoded. Example from peripherals setup for 'phase cutting' with a Triac in my project:

const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);
bool periF = (pinDesc.ulPinAttribute & PIN_ATTR_TIMER_ALT);

// setup the pin as TCC wave out pin
pinPeripheral(triacPin, periF ? PIO_TIMER_ALT : PIO_TIMER);

TCC->CC[tcChannel].reg = PULSE_PERIOD;


Unexpected results when creating 32-bit int from byte array

The problem is that you are trying to shift uint8_t more than 8 bits and then OR it with int32_t.

You have to cast the uint8_t to int32_t before doing the shift.

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

void loop()
{
    uint8_t bytes[4] = { 0x00, 0x04, 0x4F, 0x45}; //00044F45
    int32_t theInt = byteArrayToInt32(bytes);
    Serial.println(theInt, HEX); //Print 4F45
    delay(1000);
}

int32_t byteArrayToInt32(uint8_t* bytes)
{
    int32_t i = 0;
    i |= (int32_t) bytes[0] << 24;
    i |= (int32_t) bytes[1] << 16;
    i |= (int32_t) bytes[2] <<  8;
    i |= (int32_t) bytes[3];
    return i;
}


The easiest things to do if space is a premium is to unsolder (or cut) the pins and then solder directly the wire to the corresponding spots.

Otherwise, you can also just get straight pins and replace them, You can also choose on which side of the board, as the holes are though it.

Lastly, about bending, it's doable with pliers if you want to make the pins face "forward" but depending on the quality of your pins they might break in the operation.


Several ESP8266 in wifi network should share information

I guess you are asking if it is feasible: if this is the case, I would say yes, without too many troubles. Each ESP can launch MDNS discovery, so they can discover each other.


Counting the pulses is child's play and doesn't need a library (hint: use an interrupt input and increment a counter). From that count you can use TimeLib.h to convert seconds since 01/01/1970 to an actual time.  Or just do simple division to convert seconds (count/50) into minutes, hours, whatever division you want.


max current while using a shift register

0.20A is not the maximum current for an Arduino device.  0.20A is the maximum current for the chip that is on the Arduino.  Thus it is only relevant to devices that are directly connected to the Arduino's IO pins (that connect direct to the chip).

The shift registers take their own power from the +5V pin, which is limited to between 500mA and 800mA depending on how you power your board.  Each shift register has its own power limits that are completely separate to the Arduino's main chip's power limits.


How to implement a tilt compensated compass?

Inspecting your code, it does not appear you are compensating the raw magnetometer values for soft and hard iron effects.  These terms roughly refer to adjusting the range and magnitude of each of the individual magnetometers (X, Y and Z).  Some magnetometer manufactures allow writing these compensation values into the chip.  Even then the developer and user will still need to perform some form of calibration as the magnetometer can not predict under what conditions the magnetometer will be used.  Here is another explanation using matrices of hard and soft iron compensation.
Once the compass produces expected results on a flat surface parallel to the surface of the earth (in a place on earth where the magnetic lines roughly align with true north).  Consider adding tilt compensation.  Accelerometers usually do not need to be compensated as extensively as magnetometers.
This can be done using trigonometric math and Euler angles.  However, as with physical gambles, this can lead to a situation similar to gimbal lock.  Where the trigonometric math goes to infinity.
To avoid a gimbal lock like situation, most tilt compensated compasses use quaternions.  Quaternions use imaginary numbers and matrix math to describe 3 dimensional rotation.


How many transistors are there in an H Bridge?

The absolute minimum number of transistors in a H bridge is 4 (one in each leg of the "H" and the motor in the middle), but there may be more depending on what voltage and control scheme is desired.


Why doesn't data return when I use Sim808 http request

One problem I can see is the while loop has a break statement in it that "exits" the while loop before printing the data. Removing that break and printing the data out where the break "was" may help. Here's an example of what I'm trying to say:

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

void loop(){

  while(true){
    int ret = 0;
    if(ret <= 0){
      Serial.println("fetch over...");
      // Print out the received data here...
      Serial.print("Recv: ");
      Serial.print(ret);
      break;
    }
  }

}


Is Arduino IDE enough to program with C or C++?

In terms of the core language features, there's virtually no difference. In the background, the Arduino IDE and Atmel/AVR Studio both use GCC to compile the code.

GCC is an excellent toolset which supports all the core language features of C++. Admittedly, the version which currently comes with the Arduino IDE is a little old, so it doesn't support C++11 onwards. However, a lot of C++11 features are not very relevant or useful for microcontroller programming anyway (e.g. threading).

You're also likely to use the same standard library for both, which is AVR Libc. It provides pretty much all the standard C functionality that you're likely to use in an AVR project. It doesn't include the C++ stuff though, such as streams, containers, and algorithms. These tend to be very resource-hungry though, so are best avoided anyway.

The major difference is basically flexibility. Atmel/AVR Studio is designed to let you work on a wide range of projects and customize the build to suit very specific needs. You can also use alternative libraries with it more easily. In theory, the Arduino IDE can be modified in similar ways, but it's a major hassle because it provides no GUI to do it.

It's also important to note that the Arduino IDE does a number of non-standard things, such as re-organising declarations and including libraries in strange ways. It's designed to be more user-friendly, but often ends up just getting in the way. There are usually ways to work around those issues though.


Will a .ino Arduino Sketch compile directly on GCC-AVR?

See my answer here: Classes and objects: how many and which file types do I actually need to use them? - specifically: How the IDE organizes things.

  I know that at a minimum you have to include the Arduino header file

Yes you would need to do that.

  but beyond that, what would cause a compilation error if compiling said .ino to .cpp file using, say, for instance GCC-AVR.

The IDE generates function prototypes for you. Code in a .ino file may or may not need this (it probably will unless the author is disciplined enough to code in the usual C++ way and do them themselves).

If the "sketch" contains other files (eg. other .ino, .c or .cpp files) then these would need to be incorporated in the compile process as I describe in my answer mentioned above.

Also you would need to (compile and) link in any libraries used by the sketch.

You haven't asked about the linking side of things, but naturally the various files, as compiled, need to be linked together, and then turned into a .elf and .hex file for uploading purposes. See below.

Example makefile

Based on the IDE output I made a simple makefile a while back:

#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

In that particular case, the .ino file compiled without any problems after renaming it to Blink.cpp and adding this line:

#include <Arduino.h>


Unexplainable int behavior in encoder/LED project

Here:

CRGB leds[NUM_LEDS];

you are defining an array of NUM_LEDS objects of the CRGB type.
Valid indices for this array range from 0 to NUM_LEDS-1.

Here:

for (int i = 0; i <= NUM_LEDS; i++) {
  leds[i].setRGB( r, g, b );
}

you are accessing the array elements at indices 0 to NUM_LEDS. The
last iteration is an out-of-bounds access, which is causing memory
corruption. You should instead write

for (int i = 0; i < NUM_LEDS; i++) ...


Problem with structs and pointers(?) - Mega with QueueArray

It's not your C knowlede letting you down, it's just that you haven't gotten used yet to the weirdness of the arduino ide/compiler.

You do not need to create a main() function.

You need to create a loop() function.

main() is already defined and calls loop() in a loop.

Check any other sketch and you'll notice that it usually defines setup() and loop(), almost never main().

You must put in the setup function all the code that needs to be executed once (settings and initializations) and in the loop() function whatever needs to be executed iteratively.

Also, leave declarations out of loop() unless you want such variables to have scope (and life) limited to only one round of loop()


Arduino ds3231to TM1638 problems,alarm clock project

You set the variable data only in the setup function.

You also do not print out data to Serial but the output of rtc.toString(buffer).

If data is not updated in the loop method, the display constantly shows the time you initially set in the setup method.


How to interface DS1801 digital resistor with Arduino DUE SPI interface? What clock rate so use?

There is no way in hell you're going to get a 10MHz signal down that line. Shorten it to 3 inches total maximum and reduce the clock rate to 2MHz or lower. It is possible to get a 10MHz signal through, but you'd need to switch to twisted pair wiring and proper termination to even begin to have a chance to get it to work.


MemoryFree library showing Irregular Behaviour..!

Free memory can be found in two forms:

The free space between the heap and the stack. This is usually the
main chunk of free memory.
Heap “holes”, i.e. pieces of unallocated memory within the heap. The
presence of these holes is called “heap fragmentation”.

There are various versions of the MemoryFree library. The simplest ones
only report the main chunk between the heap and the stack. The more
sophisticated ones walk the malloc()'s free list in order to also count
the heap holes. Which approach is better? I would argue that the naive
version is fine, as heap holes is something you should not count on,
because it is never guaranteed that a particular allocation will fit in
any of those holes.

You are visibly using one of the naive versions. As you grow your
string, the object calls realloc(), which in some cases copies the
string's character array and frees the original one, potentially
creating a heap hole. Eventually, small holes can coalesce into a
larger one big enough for the next allocation, and
realloc() can end up using this large hole and freeing the chunk at
the top of the heap. When this happens, the heap shrinks, and the main
chunk of free memory gets larger, which is what freeMemory() is
reporting to you.

In summary, it's normal and expected behavior. If you want something
less surprising, use a version of the library that does count the holes.
But then you may run into a more displeasing surprise: a heap–stack
collision, or an out-of-memory condition, can happen even with loads of
memory buried inside heap holes.


Ok so I'm not familiar with the sheild or API (or motor lol) but going off the spec sheets etc

Leave the red wire disconnected [see 1] and try this code and report back what happens:

  #include <Wire.h>
  #include <Adafruit_MotorShield.h>
  #include "utility/Adafruit_MS_PWMServoDriver.h"

  Adafruit_MotorShield AFMS = Adafruit_MotorShield();
  Adafruit_StepperMotor *myMotor = AFMS.getStepper(64, 2); // 64 steps pr revolution
                                                           // Using M3 and M4 of shield

  void setup()
  {
    AFMS.begin();  // create with the default frequency 1.6KHz
    myMotor->setSpeed(30);  // 30 rpm, so 1 full turn every 2sec
  }

  void loop()
  {
    // 64 steps per motor shaft revolution,
    // 64 revolutions of motor per output shaft revolution
    myMotor->step(4096, FORWARD, DOUBLE);    // Should be 1 rev in one direction
    myMotor->step(4096, BACKWARD, DOUBLE);   // and 1 rev in other direction
  }

[1] : your motor is unipolar (wikipedia on unipolar and bipolar motors), according to its documentation. The red wire is the central tap, and useless in this context.


Use Wii Remote and Arduino to emulate a keyboard for Windows 10?

The Arduino Leonardo and Arduino Micro (as well as other third-party boards, such as the Teensy and the chipKIT Lenny) can be directly programmed to emulate a keyboard.  There are examples in the IDE that show how to do this.

It is possible with an Uno, but that requires replacing the firmware on the USB interface's ATMega32U4 chip with special HID firmware. This is a non-standard setup, though, and may make programming of the Arduino through the USB port impossible.  So I wouldn't recommend doing that, and would instead go for a board that can directly emulate a keyboard.

There are plenty of tutorials on the web for connecting a Wii Remote with an Arduino, (including a library), so couple that with the examples in the IDE and a suitable board and you are good to go.  From then on it's just a Simple Matter of Programming...


I used other servo library and it worked.. Then i changed the pulse width with this line of code.
The default is 1000-2000. But it rotates only 95 degrees. When it's pushed to around ~2850us the servo rotates up to 181-185 degrees.
servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);
#include <Servo_ESP32.h>

static const int servoPin = 16; //printed G14 on the board
int delayTime = 20;
Servo_ESP32 servo1;

int angle =0;
int angleStep = 5;

int angleMin =0;
int angleMax = 180;
#define CHANNEL_NOT_ATTACHED -1
void setup() {
    Serial.begin(115200);
    servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);

}

void loop() {
    for(int angle = 0; angle <= angleMax; angle +=angleStep) {
        servo1.write(angle);
        Serial.println(angle);
        delay(delayTime);
    }

    for(int angle = 180; angle >= angleMin; angle -=angleStep) {
        servo1.write(angle);
        Serial.println(angle);
        delay(delayTime);
    }
}


How do I write and read internal EEPROM?

Avoid the 'String' object, use a character array of fixed length. You might want to add one extra byte for the zero-terminator. Put everything in a 'struct' and then you can use the EEPROM.get() and EEPROM.put() to read and write the complete struct. I prefer a struct to keep the data from EEPROM together. That makes it easier to add a checksum and a version number for the data. When something is wrong with the data from EEPROM then default values could be used.

Instead of a struct, you can also read and write the seperate items. The EEPROM.get() and EEPROM.put() should be able to use a character array of fixed length.


A complete test would obviously be something fairly complex, and would
probably require building some sort of rig. You can, however, perform a
minimal test that checks for common failure modes, without connecting
any extra hardware.
I assume the pin I/O stages are the easiest thing to break. You can then
check that, when you read a pin that is set to OUTPUT, you get the
value that the pin is supposed to be outputting. You can leverage the
stray capacitances of floating pins to test them as inputs: the
capacitance should make the pin “remember” its previous output value for
some time, and that time should be really short if the internal pull-up
is enabled.
The following program tests pins 2–13 and A0–A5 of an Uno. It checks
that:

a pin set to OUPUT LOW reads LOW
a pin set to OUPUT HIGH reads HIGH
a pin switched from OUPUT HIGH to INPUT reads HIGH
a pin switched from OUPUT LOW to INPUT reads LOW
a pin switched from OUPUT LOW to INPUT_PULLUP reads LOW, then
switches to HIGH less than a microsecond later

Pins 0 and 1 are not tested, as they are connected to the serial port.
On the other hand, if you can upload a sketch, you know those pins work
at least as RX/TX.
Note that the program uses direct port access, as the Arduino functions
for accessing the pins are too slow for this kind of tests. If all
works, the program prints “All tests passed.”. Otherwise specific error
messages are printed, followed by “Some tests failed.”
#include <avr/cpufunc.h>
#include <util/delay.h>

int failures = 0;

static void log_failure(char port_name, const char * reason)
{
    failures++;
    Serial.print("FAIL: Port ");
    Serial.print(port_name);
    Serial.print(", read ");
    Serial.println(reason);
}

static inline __attribute__((always_inline))
void test_port(const char port_name, uint8_t mask,
    volatile uint8_t *pin, volatile uint8_t *ddr, volatile uint8_t *port)
{
    *port = 0;
    *ddr = mask;   // OUTPUT LOW
    _NOP();
    if ((*pin & mask) != 0)
        log_failure(port_name, "OUTPUT LOW");
    *port = mask;  // OUTPUT HIGH
    _NOP();
    if ((*pin & mask) != mask)
        log_failure(port_name, "OUTPUT HIGH");
    *ddr = 0;      // INPUT_PULLUP
    *port = 0;     // INPUT -> HIGH
    _NOP();
    if ((*pin & mask) != mask)
        log_failure(port_name, "INPUT HIGH");
    *ddr = mask;   // OUTPUT LOW
    *ddr = 0;      // INPUT -> LOW
    _NOP();
    if ((*pin & mask) != 0)
        log_failure(port_name, "INPUT LOW");
    *port = mask;  // INPUT_PULLUP
    _NOP();
    uint8_t r1 = *pin;
    _delay_us(1);
    uint8_t r2 = *pin;
    if ((r1 & mask) != 0 || (r2 & mask) != mask)
        log_failure(port_name, "INPUT_PULLUP");
}

void setup()
{
    Serial.begin(9600);
    TIMSK0 &= ~_BV(TOIE0);  // disable timer interrupt

    test_port('B', 0x3f, &PINB, &DDRB, &PORTB);  // PB0..PB5
    test_port('C', 0x3f, &PINC, &DDRC, &PORTC);  // PC0..PC5
    test_port('D', 0xfc, &PIND, &DDRD, &PORTD);  // PD2..PD7

    if (failures == 0)
        Serial.println("All tests passed.");
    else
        Serial.println("Some tests failed.");
}

void loop(){}

As an extension, analog inputs could be tested in a manner similar to
test 5: if the analog sampling is done at the right time, you can
get a reading that is somewhere mid-range.


Sure, no reason that wouldn't work. For best results you want a known resistor of about the same resistance as, or a little below, the one you are measuring.

However, if what you are seeing is an actual open circuit then there's little benefit to measuring the resistance - you may as well just treat it as a switch or button, give it a large pullup, and use a digital input (or even an interrupt) to give a simple "OK / ERROR" signal.


Flashing a ATmega328 that came from an Arduino to not use an external oscillator

Do I need an oscillator installed just so I can wake it it up and tell it to not use an oscillator?

Yes, yes you do.

Pick up a 8-16MHz crystal (not an oscillator) and two 15pF capacitors and use very, very short wires to connect them to the chip as shown in the "System Clock and Clock Options" section of the '328P datasheet. You will then be able to reprogram the fuses using AVRDUDE.


Functions like

boolean Water_Level_Check_A(){
   boolean Result = digitalRead(Water_Level_A);
   return Result;
}

Are really overcomplicated. You're just calling one function and returning that value, so it can be simplified to

boolean Water_Level_Check_A(){
   return digitalRead(Water_Level_A);
}

Or just the expression

digitalRead(Water_Level_A)

whenever you need it.

So all you're doing is calling digitalRead() on a pin number and check if the result is low. If you really want to move this to a different function then you could give it the pin number argument and directly invert the result so that a true from this function means that some action needs to be done.

boolean Water_Level_Check(int sensorPin){
   return !digitalRead(sensorPin);
}

And then call it as

void loop() {
   if (Water_Level_Check(Water_Level_A)){
       //--> Water Pump A
   }
   if (Water_Level_Check(Water_Level_B )){
       //--> Water Pump B
   }
}


You should post a higher quality version next time.

Wiring:

First of all, the button looks like it's not all the way in. Fix that first.

Also, from your picture, it looks like the green wire isn't in the right row:

I can't tell for sure. Also, like mentioned before, you to put the button over the gap between the two sides of the breadboard.

Also, you have a pullup resistor in your circuit and you enable it on the Arduino. And your physical pullup resistor isn't connected to your signal line. And you short your signal line to ground. All of this is incorrect wiring...

If utilizing the internal pullup resistor (like you are in your code), all you should need to do for a circuit is like this:

Just be sure to connect the 5V rail to 5V and the green wire to your digital pin.

Code:

That's all fine. When doing logic with a button, be sure to debounce it.


Can I avoid having a bootloader if I use ISP to flash to an arduino?

It looks like the Trinket Pro has an Atmega328P processor. You can change the fuses to not run the bootloader, in which case you don't need the space taken by it.

I have a hex uploader sketch which will upload a .hex file from an SD file directly to the chip, removing the need for a bootloader. Using ArduinoISP is another approach which will probably work. I'm not sure whether that fixes up the fuses for you.

If you just want to avoid the time (and not the space - the bootloader is probably only 512 bytes) you can use the sketch I linked to (without needing an SD card) to make fuse changes.

See Engbedded Atmel AVR® Fuse Calculator for fuse calculations. Basically you need to toggle the BOOTRST fuse (the low-order bit of the High fuse).


Sizes of the original ESP32-DevKitC-32U Wifi board

The distance of the headers is breadboard and perfboard compatible for 0.1" (2.54 mm) pin standard. 25.4 mm is 10 rows.


Your plan has more flaws. First as Juraj wrote in a comment, you can't dim a switching power supply of the LED bulb. But this would not work as you plan even if you use a classic incandescent light bulb with AC. You can't control it with PWM. AC is dimmed with phase control, which requires a zero crossing detection to turn off power for part of the AC wave.


Issue with If statement and boolean logic


There is a brilliant JSON library called ArduinoJSON. It can be installed using the arduino library manager.

See https://bblanchon.github.io/ArduinoJson/doc/decoding/ for further details.

To loop through the keys, you can use:
https://bblanchon.github.io/ArduinoJson/api/jsonobject/begin_end/

or if you know the key, you can do jsonObject["pi"] to get the value


How can I create multiple running threads?

There is no multi-process, nor multi-threading, support on the Arduino. You can do something close to multiple threads with some software though.

You want to look at Protothreads:

  Protothreads are extremely lightweight stackless threads designed for
  severely memory constrained systems, such as small embedded systems or
  wireless sensor network nodes. Protothreads provide linear code
  execution for event-driven systems implemented in C. Protothreads can
  be used with or without an underlying operating system to provide
  blocking event-handlers. Protothreads provide sequential flow of
  control without complex state machines or full multi-threading.

Of course, there is an Arduino example here with example code. This SO question might be useful, too.

ArduinoThread is a good one too.


Arduino Mega 2560 LED is dim when powered from digital output

The pinMode() arguments are backwards. As it is the LED is powered through the input pullup resistor, which is about 20-50kohm.


int laastButtons[3]; // save the previous deBounce read.
for(int x; x<4; x++)
{
   laastButtons[x] = lastButtons[x];

Well, there's a common bug right away.  An array with three slices, numbered 0, 1 and 2, and you're accessing them with a loop that counts from 0 to 3.

Spot the error.

Also, in the for loop, what number does it start counting from?

And now for your "bug".  This block of code:

if(lastButtons[x] == true)
{
  delay(50);
  lastButtons[x] = !digitalRead(button[x]);
  if(lastButtons[x] == 1){ pressed = x;}
  nt("Pressed!, Button ID: ");nt(x); nt(" pressed:  ");nt(pressed); nt(" state "); ntln(lastButtons[x]);
}

I think you have it slightly wrong.  Let's convert it into plain english:

If button is pressed:

Delay 50 ms
Read button again
If button is pressed:

Set pressed to the button number

Print the button message

Note the indenting, which highlights what gets executed for what IF statement.  The print is going to happen regardless of the setting of the pressed variable.

I think the structure you wanted is:

If button is pressed:

Delay 50 ms
Read button again
If button is pressed:

Set pressed to the button number
Print the button message

In that layout the second If is controlling both the setting of the pressed variable as well as whether or not to print the Pressed! message.

if(lastButtons[x] == 1){ pressed = x;}

That line is saying "If last buttons X is 1, then set pressed to X. That is all it is doing. Nothing more, nothing less.


Recovering from lost USB connection (Leonardo to Raspberry Pi)

The USB devices are created dynamically. You might find this question and answer from the SE Raspberry Pi helpful: How to force rescan of USB serial devices?.

You can use the dmesg(8) command on the Pi to see the messages generated by the USB sub-system. Watch the output to see if there are errors associated with the Arduino dropping off the bus. This is what the output will look like (roughly, this is from an Uno connected to a Raspbian system), note the last line which is a disconnect from unplugging the Uno from the Pi. Resetting the Uno did not do anything that the Pi saw. I would guess that that is because the reset button on the Uno doesn't reset the 16U2 (the processor handling the USB port).

[  459.936719] usb 1-1.3: new full-speed USB device number 5 using dwc_otg
[  460.051182] usb 1-1.3: New USB device found, idVendor=2a03, idProduct=0043
[  460.051212] usb 1-1.3: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[  460.051229] usb 1-1.3: Product: Arduino Uno
[  460.051245] usb 1-1.3: Manufacturer: Arduino Srl
[  460.051262] usb 1-1.3: SerialNumber: 75431343334351F061E2
[  460.088018] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device
[  460.089250] usbcore: registered new interface driver cdc_acm
[  460.089270] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters
[  534.212365] usb 1-1.3: USB disconnect, device number 5

From reading that question and its answers it appears that some versions of the Leonardo may have problems that can cause this behavior.

Another thing that might be worth looking into is the power supply for the Leonardos. If they are being powered by the Pi through the USB interface that might be pushing the capability of the Pi to provide power.


Indeed you could use a Mega. See this answer: it explains how
you can use Timer 1 on an Uno to provide two PWM channels at
25 kHz. This is the only 16-bit timer on that board. The Mega, on
the other hand, has four 16-bit timers: Timers 1, 3, 4 and 5. These
timers are almost identical to the Uno's Timer 1, except that they
provide 3 PWM channels each. So you have potentially up to
12 PWM channels that you can run at 25 kHz.

Now, look at this pinout diagram. Every pin labeled OCnx,
where n is either 1, 3, 4 or 5, and x is a letter, is a 16-bit PWM
output. Just take the code from the answer I linked to and adapt it to
the Mega. You configure all those timers in the same way, and you set
the duty cycle for pin OC3B by writing to the register OCR3B (and so
on...).


Enter timing value via keypad for bldc motor spin

As I understand it, you want to enter the speed, then the time, then '#'.

Let's imagine you want a speed of 22 and a time of 3.  The device will see 2, 2, 3, #.  How will it know whether you're asking for a speed of 22 and a time of 3, or a speed of 2 and a time of 23?  Simple answer: it cannot know.  So we need to find a way to tell it.

My suggestion: we'll enter speed followed by *, and time followed by #.  (There are other possible solutions to this.)

We also need to decide the longest number the user can enter, and what happens if they enter a longer one, or if they don't enter one at all?  Let's say the longest number is 3 digits, and if they enter a longer one, we will ignore the extra digits.  So if they enter 123456789#, we will register 123#.  (Again, there are other solutions.)

There's some stuff in your code about an LCD, but you don't mention it in the question, so I have ignored it.

Lastly, I am assuming your code to drive the motor and read keys is correct.

Here's some loop code which I hope will do the above.  It will read numbers until it finds either a * or a #, convert the number to an integer, and store it as either time or speed.  When it has both speed and time, it will spin the motor and reset the values.

void loop()
{
    // Where we will store the number as we type it.
    // This buffer is large enough for a 3-digit number, pull a null terminator
    char buffer[4];

    // The speed of the motor
    static int speed = 0;

    // The time to spin for
    static int time = 0;

    // Input up to 3 numbers until we find a * or #
    int i=0;
    while (1)
    {
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i<3)
        {
            buffer[i] = key;
            i++;
        }
        // If it's a * or #, end
        else if ('#' == key || '*' == key)
        {
            // Null terminate
            buffer[i] = 0;

            // Convert to an integer
            int value = atoi(buffer);

            // Set the appropriate value
            if ('#' == key) time = value;
            if ('*' == key) speed = value;
            break;
        }
    }

    // If we have both speed and time...
    if (speed > 0 && time > 0)
    {
        // ...spin the motor at the required speed
        myservo.write(speed);
        // ...and for the required time
        delay(time*1000);
        // ...then stop it
        myservo.write(0);

        // Reset the values for next time
        time = 0;
        speed = 0;
    }
}


How to change IIC (I2C) clock rate on MKR1000

Looking for a very short example!

easy:

1) find out the mcu used by the board;

2) look up its datasheet;

3) go to the i2c section and find the register(s) that control the i2c clock speed;

4) change it/them.

alternatively, you can take a look at the i2c initialization code and go from there.

the likely solution will be a one liner: use a mask to clear bits and then set those bits depending on your desire i2c speed.