Modifying normal doorbell to get notification

Many (most?) household doorbell systems in the US are powered by a simple transformer that converts 120V AC household electric supply to a lower voltage AC. Often 16V AC or 24V AC.

The coil and hammer form a device called a solenoid. When the coil is energized, the hammer (often also called a plunger) is forced in one direction, either up (against gravity) or against a return spring, striking one of the plates. When power is removed, gravity or the return spring pull the plunger back to the rest position, striking the other plate, forming the familiar ding-dong sound.

Power is applied or removed extremely simply -- by the momentary, normally-open pushbutton at your door. When you press the button, the solenoid is energized, and when you release it, the device returns to the normal state.

With regard to powering your Arduino, it is important to understand the difference between AC and DC power. The Arduino requires DC (direct-current) of either a regulated 5V DC into the 5V pin, or unregulated 7-12V DC into the VIN pin, or the regulated 5V DC from a USB device.

I don't know your level of electricity understanding, but there exists quite a bit of information on the difference between AC and DC power. Suffice it to say, you would need some additional circuit to rectify and filter and regulate the 16-24V AC into something between 5V and 12V DC.

Then, there is the issue of the loss of a good power tap while the button is pressed. If you measure the voltage across the contacts of the pushbutton while it is not pressed, you will likely find the full 16V AC or 24V AC, but if you measure those contacts while the button is pressed, you will read 0V AC. This means that tapping off of the pushbutton wires is not a good way to power a device that needs to remain on while reacting to the button press. Whether or not you could tap power off of the solenoid terminals is dependent on the voltage drop across the coil, and still you have the issue to convert the AC to DC at the proper voltage.

If this doorbell is near the ceiling, you will likely find the transformer mounted in the attic space above the ceiling near the doorbell (if there is attic space -- depending on your specific setup).  If there is a power outlet in this attic space, you could plug in a good quality AC-DC 5V adapter there to power the Arduino in the attic. The Arduino will need to remain electrically isolated from the doorbell circuit. To detect the pushbutton press, you could use a current transformer measuring the current flow through either of the 16V AC wires coming off of the transformer (measure with one of the the analog inputs of the Arduino), or with an Opto-isolator, with the transmitter connected to the doorbell circuit in a way that delivers a small current (10mA or so normally) to the transmitter side of the opto-isolator, and read the receiver side with a digital input pin on the Arduino.

Unfortunately, interfacing with a doorbell that uses AC power will require some good planning and evaluation of your doorbell system and how much additional circuitry you are willing to apply.

If you aren't careful, working near the transformer can be very dangerous to your life. Working with 16-24V AC will not be as dangerous to your life, but can easily damage the Arduino beyond repair in the flash of an eye. Take great care.


Can I use only Ruby or Crystal Lang with an Arduino?

You could bridging via Firmata: https://playground.arduino.cc/Interfacing/Ruby/
Another resource is https://code.tutsplus.com/articles/using-ruby-to-program-arduino--cms-21893
You will need to Flash your Arduino with Firmata and then program in Ruby.
I'm not sure if that would work with Crystal.


2 buttons, 1 servo, turn when pressed only

If you want the logic "if none of the two buttons are pressed, stop the servo immediately", then you'd express this in your loop as a if expression where you check if both buttons read LOW:

void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }

  //Are both buttons not pressed?
  if(buttonStateCC == LOW && buttonStateCW == LOW) {
    //Stop the servo.
    myservo.write(0);
  }
}

This assumes your buttons are with pull-down resistors to GND on one side and with +5V on the other side, as detailed in the Arduino tutorial. In short this means that an unpressed button reads as 0 and a pressed on reads as 1 (HIGH). This is unusual because we usually use the internal pullup resistors via the INPUT_PULLUP pinMode parameter with a switched logic (1 = unpressed, 0 = pressed).

I've also removed the line crServo = digitalRead(crSpeedDefault); because that doesn't make sense in my opinion, as I've detailed in my comment.


The description in the link of where you bought the strip says:

  Description:

  LED Type: 5050SMD with External IC WS2811 （1 IC control 3leds）

So, this is probably as intended.

Note the application circuits in the datasheet for the controller IC (WS2811) [Page 5] where, for 5V, you can address a single LED, but for a 12V configuration, you must group the LEDs in sets of 3.


There is no way for any hardware device, Arduino or otherwise, to request information like that from a computer.

HID is a protocol which (when used as a keyboard) allows you to send keypresses, including "media keys", which tell the computer to change the volume (amongst other things). There is no provision, other than three status LEDs, for getting any data back from the computer.

You will have to write software for your computer to query that information using whatever API may be available for your operating system, and pass that information through whatever communication channel you choose to the Arduino (such as through serial).

Some pointers:

C# get master volume level/precent
Windows 7 Master Volume
Arduino: Sending and Receiving Multi-Digit Integers


How is LED powered when PIN 2 is disconnected?

The pinMode(buttonPin, INPUT); line tells the board to set the buttonPin in high impedance mode.

When you disconnect the wire the state of that pin becomes unknown; usually it oscillates.
Since it is oscillating, the LED turns on and off randomly: you see it "dimly light".

The usual solution is to use a pull-up or pull-down. I suggest you to wire your buttons towards the ground, declare the pins as pinMode(buttonPin, INPUT_PULLUP); and invert the logic (i.e. buttonState = !digitalRead(buttonPin);). This way it will never oscillate again.


You can use a special voice recognition shield (for example: EasyVR Shield 3.0 - Voice Recognition Shield) to integrate a simple and basic voice recognition. I think it's a very fast and easy prototyping way...

For the use of the more complex Google Speech Recognition I would use a more powerful microcontroller (such as Raspberry PI or something like that)...


Distinguishing between multiple Infra Red Transmitters

It's a symmetry problem, you can solve it breaking the simmetry.
Options:

use three transmitter instead of four, the plane and its center is
still determined.
move one transmitter in the middle of the side of the square.
use different duty cycle for one (or more) transmitter.
use linear polarizing filters on the transmitters and a rotating filter on the camera lense.
...

I guess that also SVD could be helpful to find the pattern's center, when the camera is not centered and perpendicular.


Unable to read Arduino+ESP8266 full get Response

Finally the HTTP Get request with Arduino Uno + ESP8266 Wifi shield which is working is below:
// This is a demo example using a public http server for testing both GET and POST requests
#include <Arduino.h>
#include <LiteESP8266Client.h>

#define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

LiteESP8266 radio;

const char ssid[] PROGMEM = "xyz";    //change it to your wifi SSID
const char password[] PROGMEM = "abc";    //change it to your wifi password
const char host[] PROGMEM = "192.168.0.156";
const int port = 8080;

const char http_get_request[] PROGMEM = "GET /test HTTP/1.1\r\n";
const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
const char http_content_length_header[] PROGMEM = "Content-Length: ";
const char success[] PROGMEM = "success";
const char failed[] PROGMEM = "failed";
const char CRLF[] PROGMEM = "\r\n";
const char error_data_null[] PROGMEM = "Error: data came back null.";

void setupStationMode() {
  Serial.print("Setup station mode... ");
  if (radio.set_station_mode()) {
    Serial.println("success");
  } else {
    Serial.println("failed");
  }
}

void joinAP() {
  Serial.print("Join AP ");
  Serial.print(ssid);
  Serial.print("... ");
  if (radio.connect_to_ap(ssid, password)) {
    Serial.println("Success");
  } else {
    Serial.println("Failed");
  }
}

void establishTcpConnect() {
  Serial.print("Establish TCP Connection... ");
  if (radio.connect_progmem(host, port)) {
    Serial.println( "Success");
  } else {
    Serial.println( "Failed");
  }
}

void getHttpPacket() {
  char *data;
  while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
    if (data) {
      Serial.println("Packet Received...");
      Serial.println(data);
    } else {
      Serial.println(error_data_null);
    }
  }
  free(data);
}

void httpGet() {
  Serial.println("Sending GET request... ");
  radio.send_progmem(http_get_request);
  radio.send_progmem(http_useragent);
  radio.send_progmem(http_host);
  radio.send_progmem(http_close_connection);
}
void setup() {
  delay(2000);
  radio.begin(9600,2,3);
  Serial.begin(9600);
  while (!Serial) {};

  setupStationMode();
  joinAP();
}

void loop() {
  establishTcpConnect();

  httpGet();
  getHttpPacket();
  }

Output:
Setup station mode... success
Join AP ⸮... Success
Establish TCP Connection... Success
Sending GET request...
Packet Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 27
Date: Fri, 07 Aug 2020 13:04:03 GMT
Connection: close

Greetings from Spring Boot!

But one issue I am facing is after few call the HTTP invocation is getting stopped probably memory being full. Will check this.


A knob that can be turned by hand, have the position read, and turned by software to another position?

If you attach a knob to the Analog Feedback Micro Servo, either directly or via gears, then you can use the pot output to measure the current position and use the normal servo control protocol to turn it under software control.


Trying to read different gas levels with MQ2 Gas Sensor

First this should be like this:

float* values= mq2.read(false); //false

and then write this to be printed in the serial monitor

Serial.print('\n');
  Serial.print("LPG:");
  Serial.print(lpg);
  Serial.print(" CO:");
  Serial.print(co);

  Serial.print('\n');
  Serial.print("SMOKE:");
  Serial.print(smoke);
  Serial.print(" PPM");
  Serial.print('\n');


MB-102 BreadBoard Power Supply Limitation

Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v?

You mean because the current requirements? The answer is yes and no. No, because the needed current must not flow through the Arduino. The SIM900 draws up to 2A, that current would fry the protection diode/voltage regulator on the Arduino (though you may get away with a bit less than that by using a big capacitor to accommodate current spikes). Depending on the version of the Uno, it can provide 200mA or 1A (in case of rev3)(including what is needed for the Uno to operate). You need to provide the 5V of these modules from outside of the Arduino, via an extra voltage regulator, which can handle the big current.

  does 9v battery is enough?

If you mean the standard 9V block battery, then no, never. These batteries are meant for low power applications and are almost never a good choice for an Arduino project (unless you have really a low power application). You need to use different batteries, for example a series of AA batteries or a LiPo pack (including the needed circuitry for such a pack).


I too thought whats wrong with a normal Antenna, but the answer is the problem is the human body.

There are manufacturers that make "fabric" antennas, but these tend to be Mil-Spec so are going to cost a fortune.  (http://www.pharad.com/gps-wearable-antenna.html)

I found this site that explains what the effect of the body is, and seems to make their own antenna.  http://www.pharad.com/gps-wearable-antenna.html

I think you might be better off looking for a high gain antenna and the choice of active or passive will probably be based on the interference you get from the body.


I solved the problem by using millis() function. And now I ca get results like these;

My code is;

#include <Sensirion.h>
#include "DHT.h"
unsigned long time;

#define DHT1PIN 4
#define DHT2PIN 7

#define DHT1TYPE DHT11
#define DHT2TYPE DHT11

DHT dht1(DHT1PIN, DHT1TYPE);
DHT dht2(DHT2PIN, DHT2TYPE);

const uint8_t dataPin =  9;              // SHT serial data
const uint8_t sclkPin =  8;              // SHT serial clock
const uint8_t ledPin  = 13;              // Arduino built-in LED
const uint32_t TRHSTEP   = 1000UL;       // Sensor query period
const uint32_t BLINKSTEP =  250UL;       // LED blink period

Sensirion sht = Sensirion(dataPin, sclkPin);

uint16_t rawData;
float temperature;
float humidity;
float dewpoint;

byte ledState = 0;
byte measActive = false;
byte measType = TEMP;

unsigned long trhMillis = 0;             // Time interval tracking
unsigned long blinkMillis = 0;

void setup() {
  dht1.begin();
  dht2.begin();
  Serial.begin(9600);
  Serial.println("In.(%) In.Tem(*C) Out.(%) Time");
  pinMode(ledPin, OUTPUT);
  delay(15);                           // Wait >= 11 ms before first cmd
  // Demonstrate blocking calls
  sht.measTemp(&rawData);              // sht.meas(TEMP, &rawData, BLOCK)
  temperature = sht.calcTemp(rawData);
  sht.measHumi(&rawData);              // sht.meas(HUMI, &rawData, BLOCK)
  humidity = sht.calcHumi(rawData, temperature);
  dewpoint = sht.calcDewpoint(humidity, temperature);
  logData();
}

void loop() {

  unsigned long curMillis = millis();          // Get current time

  // Rapidly blink LED.  Blocking calls take too long to allow this.
  if (curMillis - blinkMillis >= BLINKSTEP) {  // Time to toggle the LED state?
    ledState ^= 1;
    digitalWrite(ledPin, ledState);
    blinkMillis = curMillis;
  }

  // Demonstrate non-blocking calls
  if (curMillis - trhMillis >= TRHSTEP) {      // Time for new measurements?
    measActive = true;
    measType = TEMP;
    sht.meas(TEMP, &rawData, NONBLOCK);      // Start temp measurement
    trhMillis = curMillis;
  }
  if (measActive && sht.measRdy()) {           // Note: no error checking
    if (measType == TEMP) {                  // Process temp or humi?
      measType = HUMI;
      temperature = sht.calcTemp(rawData); // Convert raw sensor data
      sht.meas(HUMI, &rawData, NONBLOCK);  // Start humidity measurement

      float h2 = dht2.readHumidity();
      float t2 = dht2.readTemperature();

      Serial.print(humidity);
      Serial.print(" \t");
      Serial.print(temperature);
      Serial.print(" \t");

      if (isnan(t2) || isnan(h2)) {
        Serial.println("Failed to read from DHT #1");
      } else {
        Serial.print(h2);
        Serial.print(" \t");

        //time = millis();
        //prints time since program started
        Serial.println(curMillis);
      }
      Serial.println();
    }
    else {
      measActive = false;
      humidity = sht.calcHumi(rawData, temperature); // Convert raw sensor data
      dewpoint = sht.calcDewpoint(humidity, temperature);
      logData();
    }
  }
}

void logData() {
}

But the difference is that I am using SHT75 instead of another DHT11 so I am simultaneously acquiring data from the both of them. Thanks for everyone!


My Arduino smokes every time I connect an AC/DC wall adapter to it. Can someone help me to fix it?

As already stated in the comments, the voltage of your power supply is the problem. The Arduino has a linear voltage regulator at the Vin pin. It dissipates the excess voltage as heat. The higher the supplied voltage, the lower the current, that you can draw before it overheats. The regulator on a genuine Arduino should go into thermal shutdown, while the regulators on most cheap clones will just get destroyed.

19.5V is too high for the Arduino. The Vin pin is meant for  6 to 12V max. You need a power supply, that can provide a voltage in that range. Or you can buy a regulated power supply, that directly gives you the 5V, that the Arduino needs.

Also you should be really carefull with powering the motor through the Arduinos 5V pin. Motors can easily draw a big amount of current. When drawing too much current through the Arduino (to be specific: through the voltage regulator or the protection diode), the same as explained above will happen. Only very small motors can be supplied through the Arduino. As you use a relay to control it, I guess the motor draws a lot of current. You need tp connect it directly to a fitting power supply, so that the current for it does not flow through the Arduino.

And always be sure, that the used parts can work with the voltage, that you want to supply, including the motor.


Use SD Card while Pin 11 is being used for PWM

The program you link to does not take over pins 3, 9, 10 and 11, it
takes over Timer 1 and Timer 2, which are used to provide PWM capability
on those pins. This means you cannot do analogWrite() on those pins
anymore, but you still can use them for other purposes, including SPI
access to an SD card.

Note, however, this line of code:

int speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

This of course will conflict the SPI port using pin 11 as MOSI. You can
fix this conflict simply by setting speakerPin to 3 instead of 11.


When the internal pullups are activated, a small amount of current is sourced by the pin's circuitry whenever the input is low.

That means that to drive the signal low, an external driver must not only sink current to discharge the capacitance of the internal and external circuitry, but it must continue doing so to dominate the attempt of the internal pullup to make the line high so that the voltage of the resistive voltage divider formed by the internal and external resistors is low enough to be an unambiguous low.

This means that the external circuit must be stronger - not normally a problem for an active device, but potentially an issue for monitoring some very high impedance external circuit.  So for example, if you wanted an external pull-down resistor, it would have to be substantially lower in value than the internal pull-up.

It also makes low power design (long life on batteries) difficult, as a system cannot take advantage of the best micropower suspend modes when any signal is being asserted against the direction of a pulling resistor.  With just one or two such cases you might still get reasonable life when using flashlight batteries, but not with a coin cell, something a well designed ATmega circuit can presently do.

After seeing Igor's comment, and re-reading your post, it seems maybe you are asking why the default is to have them disabled, rather than why you have the ability enable/disable them at all.  Most likely, the reason the Arduino core software has them disabled by default is because the ATmega resets that way.  As to why the ATmega resets that way, you might have to ask the design engineers, but generally it has been the norm to have an MCU reset to a state where it has the least influence on the external circuitry.  However, that is not necessarily the best - floating (undriven) inputs can potentially cause a typical CMOS input structure to consume more power than ones weakly driven to a known value.


Assigning array variables to int variables

You really don't need to maintain a list.

Just calculate the LED index from the location:

int room = 14;
int floor = 2;

const int rooms = 92;

int led = room + (floor * rooms);

That is, each floor below the current one (floors and rooms count from 0) is a full row of rooms (92 * floors), and there are "room" extra rooms on this floor to add to it.

You could make a macro:

#define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

Then your LED number is just:

int led = LEDNO(2, 14);

Here's an example taken from your code:

void floorsup(){

  FastLED.setBrightness(brightness);

  for(int a=1;a<255;a+=40){
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds2[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds3[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
  }
}


How do I make two (or more) pins available on my server url?

It looks like you forgot to initialize switchPin1 to be an output.
Add the following to your setup() (for example, right after the corresponding initialization commands for switchPin0):
void setup() {
    ....
    pinMode(switchPin1, OUTPUT);
    digitalWrite(switchPin1, HIGH);
    ....
}


LCD Weather Station - "Press To Start" Function

As Majenko points out in his comment, a couple of your if statements have the assignment operator (ie. =) whereas you are actually after the comparison operator (ie. ==).

if (buttonState = 0)

should be:

if (buttonState == 0)

And

if (buttonState = 1) {

should be:

if (buttonState == 1) {

When an assignment is used, the if statement will execute if the value being assigned is a non-zero. For more information see Using assignment as a condition expression? over on Stack Overflow.


Upload application from Visual Studio 2019 with PlatformIO

I have final solution for uploading application from VS 2019.

Visual Studio have Tools > External Tools... where is possible add the PlatformIO command for uploading application pio run -v -t upload

After that is possible adding custom button to Toolbar
Fantastic thing is, that during upload you can Stop the process


Purpose of USB (FTDI) and ICSP connectors

The ICSP is used for 'bare metal' programming. This what you'd use if you wanted to replace or remove the bootloader, change the clock oscillator settings, or program the device as a bare 328.

The USB port is for communicating with a program running on the Arduino. When it's first booted, the bootloader program checks to see if there's any activity on the serial link from the Arduino host program on a PC. If there is, then it allows downloading of a program from it. If not, it continues on to the last code that was programmed into it.

The easiest way to see whether a bootloader is installed is simply to start it up with the PC host, and see whether it can talk to it.


Reading a 10-byte buffer out of a PROGMEM string stored in a string table

The first thing you need to fix is this:

/home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino: In function 'foo()':
/home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino:42:27: warning: iteration 3276 invokes undefined behavior [-Waggressive-loop-optimizations]
     baseIndex += CHUNKSIZE;

You are adding 10 to 32760 hoping to be >= sizeof(code) however now baseIndex will become negative as an int goes from -32768 to +32767.

There were some interesting subtleties to getting this working. :)

One of your major problems is this:

const char * const scriptTable[] PROGMEM =

That will give you 2-byte pointers (const char *) which will not be large enough to index into 89400 characters.

So you need to have an array of 4-byte pointers like this:

uint_farptr_t  scriptTable [TABLE_SIZE] =

However you can't just initialize those like you tried to. That has to be done procedurally with a macro that pulls in the full address. My working code is below:

#include "code.cpp"

const int TABLE_SIZE = 3;
uint_farptr_t  scriptTable [TABLE_SIZE];  // values calculated at runtime
const int scriptLengths[TABLE_SIZE]
  {
  sizeof (script1),
  sizeof (script2),
  sizeof (script3)
  };

void foo ()
{
  // for each of the three script strings
  for (byte tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++)
    {
    // Chunk up large script strings in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    long baseIndex = 0;

    Serial.println ("----------------");
    Serial.print("tableIndex: ");
    Serial.println(tableIndex);
    long strLength = scriptLengths[tableIndex];
    Serial.print("length script string: ");
    Serial.println(strLength);

    while (baseIndex < strLength) {
      int chunk;
      if (baseIndex + CHUNKSIZE > strLength) {
        chunk = strLength - baseIndex;
      }
      else {
        chunk = CHUNKSIZE;
      }
      memcpy_PF(workingSpace, scriptTable [tableIndex] + baseIndex, chunk);
      workingSpace[chunk] = '\0';

      // for debugging
      Serial.print("#");
      Serial.print(baseIndex);
      Serial.print("- Got a chunk [");
      Serial.print(workingSpace);
      Serial.println("]");
      delay (50);
      baseIndex += CHUNKSIZE;
    } // end of while
  } // end of for
} // end of foo

void setup()
{
  // get proper pointers to the various pieces of progmem
  scriptTable [0] = pgm_get_far_address (script1);
  scriptTable [1] = pgm_get_far_address (script2);
  scriptTable [2] = pgm_get_far_address (script3);

  Serial.begin (115200);
  foo ();
}

void loop()
{
}

The file "code.cpp" just has the actual data in it (generated at http://www.lipsum.com).

As in:

#include <Arduino.h>

const char script1[] PROGMEM =  {

"Lorem ipsum dolor sit amet, consectetur adipiscing elit.  ... " };

const char script2[] PROGMEM =  {

"Aliquam erat volutpat. Praesent aliquet accumsan arcu,  ... " };

const char script3[] PROGMEM =  {

"Ut neque dolor, condimentum ut odio iaculis,  ... " };

Output:

----------------
tableIndex: 0
length script string: 32767
#0- Got a chunk [Lorem ipsu]
#10- Got a chunk [m dolor si]
#20- Got a chunk [t amet, co]
#30- Got a chunk [nsectetur ]
#40- Got a chunk [adipiscing]
#50- Got a chunk [ elit. Pro]
#60- Got a chunk [in sit ame]
#70- Got a chunk [t purus cu]
#80- Got a chunk [rsus, dict]
#90- Got a chunk [um magna q]
#100- Got a chunk [uis, place]
#110- Got a chunk [rat dui. I]
#120- Got a chunk [nteger ali]

...

#32700- Got a chunk [, eget tem]
#32710- Got a chunk [por dui te]
#32720- Got a chunk [mpor a. Do]
#32730- Got a chunk [nec malesu]
#32740- Got a chunk [ada mi et ]
#32750- Got a chunk [dolor cras]
#32760- Got a chunk [ amet.]
----------------
tableIndex: 1
length script string: 32767
#0- Got a chunk [Aliquam er]
#10- Got a chunk [at volutpa]
#20- Got a chunk [t. Praesen]
#30- Got a chunk [t aliquet ]

It successfully transitioned from the first array to the second one.


Suddently, "avrdude: Device signature = 0x000000" with ArduinoISP. Is my chip dead?

Mostly this error is due to connections/powering issues (as already mentioned in your output ).

Check connections, especially power and ground also check the
resistance between Vcc and GND of your target MCU. (If it's less than
100ohm that means something is off in your circuitry or your MCU is
already fried.)
Check if your MCU is actually getting enough power (voltage and current) also check if it's getting excess voltage.
Make sure there is proper "common grounding" done between devices.
If you are sure that the above points are checked and you still get the error try the override flag -F (avrdude through shell/command-line) and if you are still not able to upload try the manually changing the address (not recommended ) in your arduino's library so that it matches with the signature it's receiving.
Finally try using a direct USB interface with atmega32u4 as atmega32u4 supports it and upload the bootloader again through an old software called Flip after that try again.

After all this if you are not able to upload then probably your MCU is dead and it might be due to an unnoticed wrong power connection or short circuit or unintentional fuse reconfiguration (highly unlikely).


"SSD1306 allocation failed" when #include SD.h

I was able to make it all fit by using the text-only library for the OLED.

SSD1306Ascii Library

Much thanks to Majenko for explaining the problem and greiman for writing the library!


How to set cables to connect Cp2102 to Pro Mini?

RST to RST. Ignore the others, they are irrelevant.


Are there any constants for default SPI port pins defined?

Yes there are. They are defined in pins_arduino.h Below the pins for the yun.

// Map SPI port to 'new' pins D14..D17
static const uint8_t SS   = 17;
static const uint8_t MOSI = 16;
static const uint8_t MISO = 14;
static const uint8_t SCK  = 15;

Use SS MOSI MISO and SCK in your code


Could an `analogWrite` command and its variable output values be used to power multiple leds with same intensity?

Single LEDs like the standard 5mm leds work from low voltages such as 1.7 - 2.1v, so can be directly driven via an Arduino pin (through a resistor to prevent excess current draw which would damage the pin).

LED strips such as automotive LED strips (12v) require the use of a relay if you are simply switching the LEDs on and off. You can't run the relay directly from an Arduino pin, you will need to use a transistor to act as a buffer between the relay and the Arduino to prevent damaging the Arduino. Instead of the motor and diode in the below diagram, you connect your 12v led strip.

If you want to control intensity, you will need to use a transistor, or a mosfet (mosfets are easier). You can then use AnalogWrite to control the intensity of the LEDs via the MOSFET. You will need to connect the control pin for the MOSFET to one of the PWM-capable pins on the Arduino (the pins which have the ~ mark next to them), otherwise you will only be able to switch the MOSFET on and off, similar to the Relay. This site has a good guide on how to do this with a MOSFET. It also has a guide on how to use a transistor, but I can't include the link yet due to not enough reputation points. It shows both the code needed, and how to connect the components to the Arduino.


Doesn't Arduino reports DSR (Data Set Ready) correctly?

No, it does not, and can not for the simple reason that there is no DSR line connected to the processor.

Generally host software / serial driver configuration ignores DSR.

On the boards with an 8u2/16u2 the custom firmware therein can report whatever virtual state of the signal it is programmed to. On those with hardware USB-serial they will report however the pin is hard wired, or whatever value it is pulled to or floating at.

None of these (possibly excepting a Leonardo type board or an ARM one with native USB) reflect anything about the state of the target processor, so software hoping to talk to an Arduino should ignore the DSR signal.


When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.

Are you certain of that? It is incredibly unlikely that mere time will corrupt characters and data as they are read and sent - especially the minuscule amounts of time we are talking here.

  Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?

Yes, and you are already doing so, since you can't send direct from EEPROM to WiFi - you have to go via SRAM. You read from EEPROM into SRAM then send from SRAM through WiFi. You just won't be doing it an entire string at once.

  I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.

No, it doesn't. PROGMEM is for storing strings and other data within your sketch. It has nothing at all to do with EEPROM.

  I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier. If I can't figure it out I'll post the code for more direct answers.

Without seeing your code no one is really going to be able to help you. I suspect (although I am stabbing wildly in the dark) that your EEPROM reading/writing code is completely wrong and you aren't actually storing the data you expect in the EEPROM, nor reading it back properly. Unless we see your code we can't know what is going on, and so we don't have a cat's hope in hell of diagnosing your problem.


You should forget about MIME, that is only needed if you are sending multiple files to the server. Your best bet is to just send these headers, then a blank line, then your data:

POST /api/users HTTP/1.1
Accept: */*
Content-Type: application/octet-stream
Content-Length: 123

On the other end, you just look at "request.body" and it should have your binary data. (Replace 123 with sizeof(buffer))


You have

int read_LCD_buttons;

int read_LCD_buttons()
{
//..
}

You can't have a variable int read_LCD_buttons at the same time as a function called read_LCD_buttons -- this identifier is already taken. It looks however like you're not assigning or reading anything from this variable, so it probably never should have existed in the first place -- deletion is the solution.

In the case that you wanted to write a function prototype (which you by the way don't have to write in the Arduino IDE because it autogenerates them), the correct form would have been

int read_LCD_buttons();

i.e., the exact same prototype ended by a ;.

In setup() you have a random i which doesn't belong there.

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i //delete this line
}

Finally, you have a mismatch of opening and closing curly braces. Always format your code correctly, so that these errors are more easily spotted! You have one final } too much.

void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");

      if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
        lcd.clear();
        lcd.setCursor(7, 0);
        lcd.print("fish");
      }
    }
  }
}
} //This } is too much!

Then you'll also see that the third if statment which checks for a sum is actually within another expression where it was asserted that the sum is already 7. Then the inner if can never become true. You probably meant to move the if to the outer part, i.e. write

void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");
    }
    //the line below is still wrong
    if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("fish");
    }
  }
}

Next, this expression makes no sense.

if (diceOne + diceTwo == 3,2,1,5,4,6)

I think you meant that "if the sum of diceOne and diceTwo are equal to either 3, 2, 1, 5, 4, or 6 (i.e. within 1 and 6 inclusive), then do something.

Using multiple or statments this would be expressed as

if ((diceOne + diceTwo == 3) || (diceOne + diceTwo == 2) || (diceOne + diceTwo == 1) || (diceOne + diceTwo == 5) ||(diceOne + diceTwo == 4) || (diceOne + diceTwo == 6))

Or using the simpler interval check, assuming both numbers are positive and greater than 1.

if( diceOne + diceTwo <= 6)

Also this expression is suspect

if (reading<BUTTON4LOW && reading<BUTTON4HIGH)

When you have a LOW and a HIGH boundary and you want to check if reading is between these, you would write it as "if reading is greater than the lower boundary and less than the higher boundary", i.e.,

if (reading > BUTTON4LOW && reading < BUTTON4HIGH)


Light up multiple LEDs with standard Arduino Uno

Probably the simple answer is to use 63 8-bit shift registers, with a LED and resistor attached to each shift register output pin. There are many good examples of using shift registers to add output ports on the internet.

The shift register solution will let you turn on just one LED at a time, or if your power supply can stand it, all 500 at once.

This question shows how to go about the expansion Is there a way to have more than 14 Output pins on arduino?
It also gives some other valid options.


Error Outputting Values Arduino Serial.print

There's two problems here.
First, you don't enter "234", you enter "2" followed by "3" and finally "4". Your really small timeout doesn't give the digits enough time to arrive.
Second, your line ending is being received and interpreted as "not a number" which is returned as 0 by .toInt().
What you need to do is:

Don't set a short timeout - you can remove that line entirely.
Use .readStringUntil('\n') to read up until your line ending in one go.


What is the difference between Accelerometer, Gyro, and Magnetometer Sensor?

The Accelerometer measures total acceleration on the vehicle, including the static acceleration from gravity it would experience even when its not moving.

The magnetometer measures the magnetic field around the robot, including the static magnetic field pointing approximately north caused by the earth. Being placed in/around a metal frame or any large motors, diving over/around underground metal pipes or electrical equipment will all make large and noticeable effects on its measurements.

The Gyroscope measures your instantaneous angular momentum around each axis, basically how fast its rotating. Note that angular momentum is not directly compatible with euler angles, but works out similarly for small angles. Very high quality signal in the short term because there isn't much noise, but since your angular position has to be integrated off of the gyroscope, it will build up error.

Gravity is your best reference for angular position, because it doesn't drift like the gyroscope and since your robot is operating in (and causing) a sea of magnetic disturbances, using north is risky. It will not work if you are experiencing a significant acceleration though.

The simplest code would just use the accelerometer for rotations around x and y, the mag for z, and ignore disturbances. The basic idea is "I know gravity is actually down, but its being measured on the accel X axis, so I must be pitched by some amount". The Better sensor fusion algorithms will use the accelerometer/magnetometer to correct for drift in the gyro, but get most of its information about rotational position from the Gyroscope.

Tracking lateral position using a standard 9-dof IMU is not possible. Only the accelerometer measures lateral motion at all, and it needs to be integrated twice to get position. Error builds so fast your position estimate is complete garbage within seconds.

Tracking angular position is possible because all three sensors measure it in one way or another. Angles are tricky though because they are not commutative. If the gyro measures a 90 degree yaw then a 90 degree pitch from north, you are facing down; if it measures a 90 degree pitch and then a 90 degree yaw from north, your facing east turned on your side. Be careful with the math, or download an arduino IMU library that has it taken care of for you.


What you've described (without source code and/or a circuit diagram) sounds like you'll probably be using interrupts at least for the zero crossing detection. And probably the IR receiver too. The IR receiver is going to be your problem since the zero crossing is a very quick flag set and you're out of the interrupt.

On the other hand, the IR detection is going to take time, and if you're doing THAT in an interrupt you're going to be missing dozens of crossings.

To mix the two you can leave the zero crossing in it's own interrupt, but you're probably better off handling the IR in the loop via a state machine.

Since you say that neither are working, I'm going to hazard a guess and you're using the same interrupt or badly implemented them (possibly a timer and interrupt clash) and until you post some code people here aren't going to be able to help you any more than that.


How to control continuous rotation servo via HC-12 rf module

You can't rely on a specific delay being one rotation - especially when you are using SoftwareSerial. SoftwareSerial breaks many things, and anything that uses interrupts (such as the Servo library) gets broken by it. It's a real interrupt hog.

The proper way of doing it is to use a rotary encoder on the servo to report the position (or change in position) so that you know where the servo is. That's really the only reliable method of getting the servo to perform precise operations.

By the way:

mySerial.flush();//clear the serial buffer for unwanted inputs

does absolutely nothing. The operation of flush() changed when the Arduino API turned one. It is now supposed to wait until both the TX circular buffer and the UART TX FIFO are empty. It has nothing to do with emptying any inputs.  Instead you want:

while (mySerial.read() != -1);


How do you control the amount of times the void loop loops per second?

The number of times loop() runs every second depends on the time taken for the execution of the instructions within loop(). For instance, in your code, the time taken for one loop() is roughly equal to the time taken for the MCU to execute all the statements in loop() (more specifically, the time taken for each operation or function from call to return): in your case, the time taken for the Serial.print()s + the time taken for the analogRead()s (not considering any interrupts between statements).

That said, you generally don't want to control the interval between loop()s; I assume you actually want to control the interval between the execution of certain operations within your loop(). Say, you want to set the time between executions of analogRead(0) to 500 ms. This can be done like this:

#define INTERVAL 500   // time between reads
unsigned long lastRead = 0;

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

void loop(){
  //....your other code....

  if (millis() - lastRead >= INTERVAL){  // if INTERVAL has passed
    val = analogRead(0);
    lastRead = millis();
    Serial.println(val);
    //...anything else
  }

  //...your other code...
}

With this code, you now have about 2 analogRead samples every second. Of course, this is only useful if loop() runs faster than your chosen interval. If there are function calls, or any operations otherwise, in loop() (within or outside the IF block) that always take more time than your interval, then this code would serve no purpose.


You can use the old software serial library from mikal heart. that one does not die interupts. You can do a google search on it.

here is a forum topic about it:
http://forum.arduino.cc/index.php?topic=82596.0


Arduino IDEs v.1.6.x have recently been causing such kind of trouble on windows and mac systems. These problems seem to be caused by Java issues. Arduino IDE comes with java suit for it to work, installing java separately will cause problems. I suggest you uninstall java completely(by that i mean even the residue files that are not removed after uninstalling. For removing java completely you can use third party java remover like JavaRa ( https://singularlabs.com/software/javara/ ).
After doing so you can install the IDE again (i suggest to use .zip download of the IDE).
If it does'nt help it check this out http://forum.arduino.cc/index.php?topic=341144.0
its possible that problem is caused by out dated executables after updating the IDE.

Hope it helps.


From my understanding it's just retrieving subsequent samples from the DMA buffer, which means you will alternately get left and right samples from each read. It would be more normal to use the read(buffer, len) variant to read two (or more) samples at once.
int16_t pair[2]; // change to int32_t for 32 bit samples
I2S.read(pair, sizeof(pair));


Controlling an analog potentiometer using an Arduino

The first problem we have is that replacing the original potentiometer might be wrong thing to do. Analog audio hardware is usually nonlinear, because the volume of the sound is actually a logarithmic function. So the potentiometers might be fine tuned specifically for particular device, and impossible to acquire today since it's vintage.

I suggest a different approach. Connect the knobs to rotary encoders, or cheap linear potentiometers. That way you will receive data about what the user is doing, and what setting does he want to change. They usually are small and you might even fit an extra el-cheapo 28BYJ485V stepper motor to move the knobs to provide feedback. (It can be modified doubling it's torque)

Move all the audio potentiometers inside the case of the device and connect them directly to a stepper motor or a servo to move them only with Arduino.


Why is AREF connected to a capacitor in the Arduino Pro Mini Schematic?

On the datasheet for the Atmega328P, in the Analog-to-Digital Converter section, is the sentence:

  The voltage reference may be externally decoupled at the AREF pin by a capacitor for better noise performance.

Also:

  The internal voltage reference may thus be decoupled by an external capacitor at the AREF pin to improve noise immunity.

Thus the capacitor is there to reduce noise on the AREF pin.


I think the default baud rate of ESP8266 is 115200.


Can I use micros() to analyze TX23 anemometer signal?

You should really make use of pulseIn() to work out the bit rate of the signal.  The first HIGH pulse in the header is there for timing so you know how often to poll the input.

Step one, after sending your outgoing initiation pulse, should be to wait for that first pulse (you might need a slight delay first before it starts transmitting - wait for the line to be low first):

while (digitalRead(dataPin) == HIGH); // Wait for TX start
uint32_t pulseWidth = pulseIn(dataPin, HIGH); // Get first pulse

That gives you the width of the first pulse in microseconds.

Now you can read 45 times at that period.  If you first delay by half that amount before your first sample you will be roughly in the middle of the bit so you can cope with a slight amount of drift.

// Wait for the middle of the first bit
delayMicroseconds(pulseWidth / 2);

uint32_t highBlock = 0;
uint32_t lowBlock = 0;
for (int i = 0; i < 45; i++) {
    // Shift the high 32-bits left one bit
    highBlock <<= 1;
    // Place in the highest bit of the low block as the lowest
    // bit of the high block
    highBlock |= (lowBlock & 0x80000000UL ? 1 : 0);
    // Shift the low 32-bits left one bit
    lowBlock <<= 1;
    // Add in the value of the bit from the data pin
    lowBlock |= digitalRead(dataPin);
    // Wait for the next bit
    delayMicroseconds(pulseWidth);
}

You should now have two 32-bit words which, when put together, form the entire datagram.  You can now use bitwise operators to pull out the parts you are interested in.

A better, though more complex, method of doing it would be to employ a timer with an overflow period equal to the pulse width. That will afford you much more accurate timing than a simple loop with delays.


You should check to make sure that your Java installation is up to date. It would also be best to make sure that you're bit types between the Java environment and the Arduino IDE are the same(32bit with 32bit, 64bit with 64bit). If this does not work, you should post your actual errors so we can help more :)


Arduino + ultrasonic rangefinder behaving unexpectedly

I do not really understand the behaviour of your program, but I would
like to point out a couple of points that may be problematic:

Your comment says “Sends a 10 µs HIGH signal to the trigPin”, just as
the program you based yours on, yet you have a 30 µs delay. If
this extra delay makes you miss the rising edge on the echo pin, then
pulseIn() will believe it is seen the previous pulse, and it will
wait for the next raising edge before starting its measurement. Since
that next rising edge will never happen, pulseIn() will eventually
time out after one second. This is probably the silence you are
hearing.
Your sound frequency may not be what you expect, because the time
needed to run through the loop is not only the two calls to
delay(), but also the time taken by pulseIn() and the various
delayMicroseconds(). You should have more consistent timings if you
use the tone() function instead of trying to bit-bang the sound.


SD Card store struct: force big-endian / little-endian?

Many full C libraries have an sys/endian.h header file. This defines a number of macros so you can find out what the endianness of your device is.  It also usually defines a number of handy macros that can convert the endianness for you.

htobe16(x)
htobe32(x)
betoh16(x)
betoh32(x)

These convert Host to Big Endian values and back again.

htole16(x)
htole32(x)
letoh16(x)
letoh32(x)

And these convert Host to Little Endian values and back again.

Not many embedded C libraries provide it, though, and not all that do provide the handy macros.

It's not too hard to implement yourself, but it does mean you deciding what to do depending on the target architecture. Which kind of negates the handiness of the endian.h file.

So really you want to re-implement the functionality in a form you can include in all your sketches.

Fortunately the compiler provides a set of macros defining the endianness that you can use though:

#define __ORDER_LITTLE_ENDIAN__ 1234
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __ORDER_PDP_ENDIAN__ 3412
#define __ORDER_BIG_ENDIAN__ 4321
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__

So you can examine the __BYTE_ORDER__ macro to see what byte order it equates to and use that to select whether htobe32(x) has to do anything to the byte order or not.

In the PIC32 compiler it's done as a set of macros that either call swap32 / swap16, or pass the value unchanged:

#if __BYTE_ORDER__ == __LITTLE_ENDIAN__

#define htobe16 swap16
#define htobe32 swap32
#define betoh16 swap16
#define betoh32 swap32

#define htole16(x) (x)
#define htole32(x) (x)
#define letoh16(x) (x)
#define letoh32(x) (x)

#endif /* __BYTE_ORDER__ */

#if __BYTE_ORDER__ == __BIG_ENDIAN__

#define htole16 swap16
#define htole32 swap32
#define letoh16 swap16
#define letoh32 swap32

#define htobe16(x) (x)
#define htobe32(x) (x)
#define betoh16(x) (x)
#define betoh32(x) (x)

#endif /* __BYTE_ORDER__ */

So now depending on the byte order it will either swap the bytes around, or leave them unchanged.  It's now just a matter of implementing swap16 and swap32 - which I'll leave to you (hint: it just returns the value with the bytes in the reverse order - bit shifting and masking is good for that).

Then you need to decide on an endianness for your file.  Maybe choose little-endian since that is probably the most common.  So whenever you place a value into a struct for writing you pass it through either htole32(...) or htole16(...) depending on the data type.  Then whenever you read from a struct that has been read you pass the value through either letoh32(...) or letoh16(...) to get it in the host's endianness.


How to safely remove arduino nano from breadboard?

How do you usually remove the nano board from breadboard safely? And

If you can't remove it by hand (grip it lengthwise and ease up each end with your finger / thumb levering against the breadboard) then you need a lever. The best is a plastic spudger, such as this:

The plastic will flex rather than damage the Arduino. Using a screwdriver can, as you have noticed, damage the Arduino.

  The tantalum i broke is 4.7uF smd. I can't find any 4.7uF tantalum in nearby shops, but i have electrolyte caps rated 4.7uF 16v. Can i use it for replacement?

Sure. All that is, is a reservoir capacitor on the USB input. The value isn't super-critical, as long as the voltage is above 5V. It's not, strictly speaking, even needed. You can just remove it completely and clean up the pads to ensure there's no shorts. The board should still work fine.


Estimate soc battery and discharge time using Arduino Uno

Use google and enter: arduino state of charge. I got a few hits About 2,620,000 results (0.55 seconds).


I have figured out my issue, at least I am getting good results. With this code I had to change interrupts from CHANGE to RISING. I want to thank everyone that has made comments on this question. –


Gratuitious instantiation of `Serial`, why?

My guess (though I didn't check) is that it is a side effect of the fact
that the same file contains the instantiation of Serial and the
associated ISRs. The definition of the ISR macro looks roughly
like this (slightly simplified):

#define ISR(vector) extern "C" \
    void __attribute__((signal, used, externally_visible)) vector(void)

The key here is the “used” attribute. It tells the compiler that the
symbol should be considered to be used, even though no code calls the
ISR (for a good reason: it's called by the hardware).

When your program is linked, the object file foo.o pulls in
HardwareSerial0.o. The linker then sees the serial ISRs which are
labeled as “used”. These in turn make use of the Serial object which
then appears to also be used.


Which code are you reading? At step 5 he wrote

  Complete code can be found on the GITHUB.

The sketch file (here is the direct link) has the following lines:

const int rxpin = 11; // pin used to receive (not used in this version)
const int txpin = 4; // pin used to send to LCD

SoftwareSerial blue(rxpin, txpin); // new serial port on pins 2 and 3

This means that the bluetooth is using a software serial on pins 11 and 4.

I don't know where you got the image you posted, but anyway that wiring is not the same as the one in the instructable. With your wiring, you can either use the software serial on pins 0 and 1, or (better) use the hardware serial. To do so, remove or comment the lines I highlighted and then replace every call to blue with Serial.


wrong leds lit in matrix display - wrong coding?

Initialize your arrays like this:

int a[3][4] = {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

...you can read more about it here.

Added later...

The following explanation came from here:

Arrays that are not explicitly divided into rows:

int M[4][5] = {10, 5, -3, 9, 0, 0, 32, 20, 1, 0, 0, 8};

...are filled like this:

int M[4][5] =
{
  {10,  5, -3, 9, 0},
  { 0, 32, 20, 1, 0},
  { 0,  8,  0, 0, 0},
  { 0,  0,  0, 0, 0}
};

As only you understand your data you will have to verify if your data is populating the array as you expect.


solved it. was simple actually. dont know how to do it with chars, but with strings there is the addition operator.
So i converted both to string and used the + operator.

char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
String string1, string2, finalstr;

and inside the loop:

dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);
string1 = String(clat);
string2 = String(clng);
finalstr = string1 + string2;

Maybe that was too much work?
If you have any smarter alternatives, please provide!


Component with controllable resistance from Arduino?

The easiest way to drive an LED with variable brightness is to use one of the pulse width modulation (PWM) output pins on an Arduino.

A PWM pin takes an input value from 0 to 255 (or is it 0/1023? I don't remember.) and converts it to a ratio of on-time to off-time. At the highest value, the output pin is in the on state, 100% of the time. At the halfway point, the output pin is HIGH 50% of the time, and LOW 50% of the time.

Our eyes average out the flashes and see a variable brightness. It works very well.

If you absolutely must have a variable resistance controlled by a digital value, there are devices known as digital potentiometers. These are variable resistors controlled by digital inputs. For an Arduino, you should think about an I2C or SPI potentiometer, which is controlled by serial port commands. You tell it the resistance you want, and it sets itself to that resistance.

As CrossRoads points out in their comment below, you still need a current limiting resistor to drive an LED from a logic pin, to protect both the LED and the output driver on the Arduino. You want to limit the current to the max current for your LED, and then use PWM to lower the brightness from the absolute max set by the current limiting resistor. CrossRoads explains how to calculate the resistor value.


You need to review your code and also the capabilities of the Arduino UNO.

int declares an integer.  So int duty = 0.5; is going to get rounded to either 0 1.
delay(0); also will not work.  The instruction will simply get skipped. Likely the reason why you get a brighter LED. Try to use delayMicroseconds(); if you need shorter time but the minimum delay you can have is 4 us for Arduino UNO.
If you are using times as short as 2 us, then from the above comment the delayMicroseconds(); function is not going to be sufficient.  Also, you should consider the loop overhead, which will be a few microseconds.

All in all this is not a great method.  If you do want to create your own PWM signals, it is much better to use the hardware timers.  For example this tutorial on the Arduino website.  You should also be able to find posts about hardware timers on Arduino SE.


Piezo buzzer not sounding well with ATmega328

If it works well with direct 5v supply and not from an Arduino pin, you probably need a transistor to drive the buzzer.

Here is an example how to drive a buzzer using a transistor:
https://www.maxphi.com/piezo-buzzer-interfacing-arduino-tutorial


Adding Attiny to Arduino IDE - attiny\variants\platform.txt file missing

Open the "Preferences" dialog in the Arduino IDE.
Click on the symbol next to "Additional Board Manager URLs"

Paste the following into the box (possibly on a new line under any existing URLs), then click OK.

https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json

Note that you can click on the circled link for a list of boards. This will open in your web browser. You may have to switch to your browser to notice it.

Click OK to close the Preferences dialog box.
In the Tools menu / Board select the Boards Manager:

Scroll down until you see the Attiny entry (or the one for the board you want), click on it to select it, and then click "Install".

Once done, close the Board Manager dialog box.
You should now be able to select Attiny from the Boards menu:

Now in the Tools menu you can select which Attiny you want to use:

Notice you can also select the appropriate clock speed in an adjacent menu item.
To program the Attiny you will need a suitable ISP (In System Programmer) such as the AVRISP programmer, or the USBtinyISP programmer.


using references to SFRs in gcc inline assembler

You could use pointers instead of references. With pointers, you have
the separate notions of “constant pointer” and “pointer to constant”. A
reference is a kind of pointer coated with syntactic sugar. However,
whereas you can have a “constant reference” (equivalent to pointer to
constant), I do not know how to declare a “reference with constant
address” (which would be the equivalent of a constant pointer). And
this is your issue: the "i" constraint in the asm statement requires
a constant.

Here is my take with pointers:

typedef volatile uint8_t * tRegister;

constexpr tRegister timer_register(tRegister a, tRegister b)
{ return MY_TIMER==0 ? a : b; }

// The `const' below is essential.
const tRegister OCRA = timer_register(&OCR0A, &OCR2A);

asm volatile("lds r24, %0" : : "i"(OCRA));

Of course, you then have to change all your OCRA = ...; statements
with *OCRA = ...;, which is awkward. But note that the avr-libc
defines the SFRs with macros equivalent to

#define OCR0A (*address_of_OCR0A)

If you want this convenience, you may have to resort to using similar
macros yourself.


Regarding your measurements, I would completely disregard the first set with Serial.println() in the loop. I would exepect the timing of this to be unreliable.

Your second set of data that you captured in a buffer looks correct, but your Frequency Estimation / timing may be wrong. I would invert a Digital Output at each loop iteration. You can measure the frequency of that with a Multimeter and your ADC sample rate would be twice that value.

For a PC or laptop power supply that's quite a common current waveform.

Without effective Power Factor Correction the current signal shown below would be quite typical (source: http://www.nlvocables.com/blog/?p=300)

You will need to calculate RMS values and it would be wise to filter the signal.

Here's an instructable I wrote on how to build and code an Arduino Yun based Electricity Monitor with Cloud Support / Temboo and Google Drive. It should be of some help to you.


Digispark Attiny85 draws more power for digital input than expected

The schematics of the digistump developer board shows that PB3 is connected to +5V over two resistors (1.5 k + 66.5) Ohms. That's the reason for the high current (5V / 1560 Ohm = 0.0032051 A). See the schematics https://s3.amazonaws.com/digistump-resources/files/97a1bb28_DigisparkSchematic.pdf

As you mentioned in a reply on my comment above, using PB2 shows the expected behavior of an AT85 IO pin.


Why do we use HX711 with load cell (Why do we need A to D conversion)?

The HX711 is nothing more than a sensitive amplifier that takes the tiny signals from a load cell and amplifies them coupled with a high resolution ADC.
You can do without the HX711 but the signals are so tiny and the Arduino ADC so low resolution that the results are useless.
You can create your own amplifier with op-amps and use the internal ADC of the Arduino, and the results will be reasonable, though the resolution will suck.
You can use another high resolution ADC chip to increase your ADC resolution so you can measure more accurate weights.
Or... you can just do it all in the one chip with the HX711.


Atmel chips (the ones used in the Arduino) have been used in all sorts of industrial appilications way before Arduino came along. Same for other micro controllers like the still popular 8051.
What you want to focus on might be the enclosure, seal it against the outside.

Rather than using a (chunky) pre-manufactured Arduino board, you'll have to pick the right chip for your application and design a board around it. http://www.atmel.com/products/microcontrollers/avr/


How do I use Sound Sensor LM393 + Speaker in Arduino

This post was awhile ago, but I wanted to offer some more definitive info for others like myself who were trying to identify it. What you have there is the Keyes KY-037 "high-sensitivity voice sensor" module. Mine came with the Inland Arduino Uno RFID Learning Kit.

Apparently the KY-037 and the KY-038 are the same except the KY-037 has a higher sensitivity microphone. I could not find any specs to quantify what that sensitivity difference is, however. Both have a LM393 voltage comparator on the board. The same Arduino code ought to work for both.

Here are a few helpful links I found, some also showing a bunch of the other Keyes modules and how to use them:

http://linksprite.com/wiki/index.php5?title=Advanced_Sensors_Kit_for_Arduino

http://brd4.braude.ac.il/~ksamuel/ElIn.31361/Lectures/022-Basic%20Definitions%20and%20Concepts%20Sensors%20and%20Actiators%202013-10-10.pdf  (Page/slide 40)

tkkrlab.nl/wiki/Arduino_37_sensors


Simple answer: use the SD library provided by the IDE.

Long answer: fopen etc are designed for use with an operating system. While it is possible to 'bend' them to work without a kernel or filesystem abstraction layer, it's not easy. The AVR compiler and libraries don't provide the facilities for doing it.

So you need to use the method that is specific to the Arduino, which is contained in a library supplied with the IDE called SD.h. It has examples with it to show you how to use it.

There are other alternatives, as well, such as the much better written FatFS that has been ported to many platforms, Arduino included.


You did not change the lastbutton, but you compared it to HIGH. Change your code to the one below.
You can more easily avoid such mistakes, if you put spaces around operators.
//sp is switchpin, lp is ledpin

int sp=2; //interrupt enabled pin (interrupt 0)
bool ledon=LOW;
bool lastbutton=LOW;
int lp=9;
void setup()
{
  Serial.begin(9600);
  pinMode(sp, INPUT);
  pinMode(lp,OUTPUT);
}

void loop()
{

   if (digitalRead(sp)==HIGH && lastbutton==LOW){
      ledon=!ledon;
      lastbutton = HIGH; // previously here was lastbutton==HIGH;
   }

   else {
     lastbutton=digitalRead(sp);
      }
   Serial.println(ledon);
   digitalWrite(lp,ledon);

     }


Adafruit_GFX setRotation not working when called from within a class

I would actually be quite surprised if outsideClassRotation() actually
worked. My guess is that it does not work as is. Maybe it did work at
some point, but then you made some subtle changes to your code and did
not check that it is still working.

Here is the deal: there are two setRotation() methods:

Adafruit_GFX::setRotation(unsigned char) does very little besides
storing the rotation angle... which is not used anyway.
Adafruit_ILI9341::setRotation(unsigned char) actually sends commands
to the LCD asking it to apply the rotation; this is the method you
want.

The problem is that these methods are not virtual, which means that
when you call them through a pointer, as in
some_pointer->setRotation(the_angle);, you get the method
corresponding to the type of the pointer, not the type of the actual
object. For example:

tft->setRotation(the_angle);     // calls Adafruit_ILI9341::setRotation()
ptrTft->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()
passed->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()

I checked this by uncommenting your call to outsideClassRotation() and
disassembling the compiled binary: both times you are calling
Adafruit_GFX::setRotation().

Solution: change your Adafruit_GFX * pointers to be of
type Adafruit_ILI9341 *, or patch Adafruit_GFX.h to make
setRotation() virtual.


Default baud for module is 9600 unless you previous set it diffrent as per the datasheet A1 F3 ## 00 00 I believe


It appears that your intent is to set TCCROB up with a 1024x prescale, and each time it counts up to 128, increment r20, and toggle the LED each time r20 overflows to zero.

That sequence ought to take 1024/16M · 128 · 256 seconds, or about 2.1 seconds, a fairly leisurely toggle rate.  If instead it's flashing a hundred or more times too fast, probably one of the comparisons is backwards.

Some of the following items might make it easier to debug the problem:

• Instead of brbc 0,..., say brcc ...
• Instead of brbs 0,..., say brcs ...
• Instead of brbs 1,..., say breq ...

That is, use proper mnemonic branch instruction names, rather than referencing SREG bits.

• If my arithmetic was correct and your branch tests were fixed, your rate would be off by a factor of two.  To fix this problem, you could replace one of the more problematic tests (testing for carry clear after cpi r17, 128) with cpi r17, 0 followed by a breq, and change the prescale factor to 256 instead of 1024, which gives 256/16M · 256 · 256 seconds, or about 1.05 seconds.

• Use named constants for register names instead of 0x04, 0x05, 0x25, and 0x26.

• Instead of your lengthy toggle sequence use EOR to toggle the value.  That is, replace

    cpi r16, 0b00000000     ; Check if r16 is set to LED OFF
    brbs 1, switchon        ; If it is, change it to ON
    ldi r16, 0b00000000     ; Otherwise, change it to OFF
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock
switchon:
    ldi r16, 0b00100000     ; Set r16 to LED ON value
    out 0x05, r16           ; Set the LED to the new state
    rjmp loop               ; Run the clock

with

    eor   r18, r16          ; Toggle LED bit
    out   PORTB, r18        ; Set the LED to the new state
    rjmp  loop              ; Go run the clock

where r16 and r18 are initialized as follows in setup:

    ldi r16, 0b00100000     ; bit mask for LED pin
    mov r18, r16


Using the Arduino compiler, is it possible to use Atmega2560 interrupt pins that are unused by Mega?

If you are not afraid of getting your hands dirty by touching hardware
registers, you can access those pins bare-metal style, using port
manipulation. You will have to read the datasheet,
specifically the section “External Interrupts” if that's what you are
after.

This works with the stock Arduino core (or even without core), which may
be interesting from a maintenance point of view, but it's not as easy to
use as the Arduino interrupt API.


How close to 5 kHz can I set the PWM frequency on an UNO pin 11?

No, you cannot have hardware PWM at 5 kHz on pin 11 of an Arduino
Uno. The closest you can get is 3.92 kHz. You get that by setting
the prescaler to 8 and configuring the timer for phase correct PWM,
instead of the fast PWM mode usually used by GRBL. Your options for
getting 5 kHz are to use either software PWM or change the pinout.

You can get a quite accurate 5 kHz PWM signal on pins 3, 9
and 10. You can do software PWM at 5 kHz on any pin, but this
is prone to have significant jitter, which your laser may well not like.


Max current

For 4 sensors I wouldn't expect problem, however, for 50 it will.
The VCC/GND pin has a maximum of 200 mA, see Arduino Pin Current Limitations.

(Update after remark of Gerben, thanks!):
However, these are for the ATMega, not the Arduino R3. See Arduino Voltage and Current. It's not an official document, but made by Gabriel Staples). It contains a lot of references. But the VCC can handle 0.5 or 1A depending on USB or battery power.

This means:
The DS1820 uses 4 mA (checking a random datasheet), so 50 * 4 = 200 mA, which is way within 500 mA/1000 mA).

Non one wire sensors (not your case)

Since you have one wire sensors the following is not applicable (just leave it here for others):

None one-wire sensors use their own GPIO pin mostly. Since the Arduino doesn't have 50 GPIO pins, especially not for analog input, you need to have external IC(s), ADCs (Analog Digital Converters) or analog multiplexers, see also connecting more than 6 analog input pins to Arduino.

One wire sensors (your case)

You might find how many ds18b20 temperature sensors can I connect to one bus interesting.


TIMER1 CTC Interrupts not working with avr-gcc

I just tried using arduino-mk https://github.com/sudar/Arduino-Makefile, and it worked, so I guess I'm just going to stick with that.


What is the cheapest way to add wifi to Arduino?

Some months have passed since my previous answer and now the ESP8266 based WiFi modules are available.

They get connected to your project serially (3.3V) and are controlled in a modem like way using AT commands.

With a pricing of round about $5 they fit the question better than my previous OpenWrt based answer.

For more information about ESP8266 ask your favorite finding machine or list news with tag ESP8266 at Hackaday.

(Old answer from the pre-ESP8266-days:)

I vote for a small router reflashed with OpenWrt like "TP-Link TL-WR703N".

It is like building an own Yùn with an Arduino of your choice...

The WR703N:

It has Ethernet, 150MBit WiFi, USB and if you want to solder, a serial console and 2 GPIO-Pins which can be turned into I2C.

This sure is not a chip- or stamp-sized solution but often cheaper than the alternatives, more powerfull and extendable.

Search the net with your favourite find'o'bot for "arduino wr703n" and you'll find lots of examples...


ORIGINAL RESPONSE, BASED ON DIFFERENT CODE

You are comparing sensorValue to see if it's ever less than minValue.

However, you have mapped sensorValue to range from 0 to 255, and minValue is set at 0. How can anything from 0-255 be less than zero?

NEW RESPONSE, BASED ON UPDATED CODE

One of your if statements: else if(sensor = baslangic) is not comparing, but assigning baslangic to sensor. To compare, use ==.

Your other if statement: else if ((start < sensor < maxval)) is wrong. C++ doesn't work this way. Maybe you want: if ((start<sensor) && (sensor<maxval))?

Instead, your statement evaluates like if ( (start<sensor) < (maxval) ), which means you are comparing the TRUE or FALSE of (start<sensor) to the int that is maxval.


434 RF Transmitter and Receiver for distance measurement problem

It is very likely you have an AGC problem. Try to slow down the measurement. The sender shall send data not often than once per second.

This idea is not fully perfect for doing a distance measurement. It measures incoming power strength - affected by walls, reflection, AGC of the receiver, and a lot more. If you have a scope, measure the waveform on the pin 3 of the module (linear out). It is not a constant voltage, I am afraid, so you need some sort of averaging too.

A tricky way to get along even if you have an AGC is to measure how long the AGC needs to settle. The AGC works as follows: it detects the signal, and within some time (say, 2ms) it will change the amplification so that the signal will look having the full amplitude.

compare on a two channel scope the signal pulse driving the transmitter
and the signal on the pin 3 of the receiver module

If you are lucky, you'll see that actually pin3 or pin2 output is delayed a bit compared to the transmitter driving pulse. The delay depends on the power of the incoming signal to the receiver, which depends on the distance.

I was able to make an acceptable distance sensor from a standard AGC enabled IR receiver using the principles above.


Which wireless technology should I use for my outside "check-if-door-is-open" project?

I agree with @Gerben - the nRF24L01+ would probably be the most suitable for your application.  It should have enough range to go 15m through a few walls, and the cost is about as cheap as you can get.

You can pick up cheap Chinese clone modules (not real nRF24L01+ but another chip that operates exactly the same) for around $2 each on eBay.  I by them by the bag full.

There are a few good libraries around for controlling them with an Arduino so programming really isn't much of a problem.

They even have the advantage that they can operate in a mesh network mode if you ever expand your system to incorporate other things.

The connection to the module is a simple 5-wire SPI interface - SDC, MOSI, MISO, Chip Enable and Command Select pins, so you don't even need to mess with lots of wires.

You can read more about using them here: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01

The best library in existence is the RF24Network library: https://github.com/maniacbug/RF24Network

If you are looking for something more self-contained and stand-alone, you might look at the ESP8266 modules which are a programmable WiFi module.  They can either interface with an Arduino to be controlled through AT commands, which is quite nasty, or they can be programmed directly using an Arduino-like API which can be obtained here: https://github.com/esp8266/Arduino

These modules are a little more expensive, but that cost is offset by not then needing an Arduino in the mix as well.  The NodeMCU is probably the easiest to work with since it contains the USB serial interface on board like an Arduino.  It also has its own Lua based programming environment if you don't mind learning another new language, but you can use it with the Arduino API for ESP8266 above.

The ESP8266 is also supported by the beta version of UECIDE


How to output a true analog voltage at output pin

You basically have three options:

Switch to an Arduino Due which has a built-in DAC which outputs a real voltage.
Add an external DAC chip (such as the MCP4821/2) to create the voltage for you
Use a low-pass filter (R-C network) on a PWM pin.

Of the three options I usually use an MCP4822 since it gives the best results and doesn't cost as much as using a Due.


Can I use analogRead to read a digital pin?

To answer the question in the title: No, you cannot use analogRead() to read a digital pin. A digital pin cannot behave as analog because it isn't connected to the ADC (Analog to Digital Converter).

If you call something equating to analogRead(15) on an Uno, then it should read pin A1. You can see the pin assignments in the board-specific versions of pins_arduino.h (shipped with the IDE):

static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Using those raw numbers directly is generally not a good idea though as it obscures your code's meaning, and will potentially make it non-portable to other boards. It's better to call something like analogRead(A1).

It's worth noting that the Arduino library fudges the pin numbers slightly. Calling analogRead(1) has the same result as calling analogRead(A1). That means that even if you tried to use analogRead() on a digital pin, it might actually end up reading an analog pin instead. Alternatively, it might just return a meaningless result, depending on the pin number you give it.


How to multitask while writing on Serial

Until you fill the transmit buffer (64 bytes by default but can be recompiled to enlarge it if you need to), Serial.print() or Serial.write() will return immediately. The characters in the buffer will be transmitted by an interrupt service routine, so essentially, the Arduino is double-tasking for that purpose. If the buffer is full when you call Serial.print() or Serial.write() or Serial.print() fills it before having sent all of its characters, those calls block (won't return) until there is buffer-space for their remaining characters.

So yes, you can do other things while the writing happens, as long as you haven't filled the buffer. You can call Serial.availableForWrite() to find out how many characters you can send without blocking.

By the way, at 115200 baud, or 11520 bytes/second, each character should take 1/11520 seconds or 86.8 microseconds, not 70 milliseconds.


Test the LED: Connect it between +5v and ground with its current-limiting resistor. Make sure the cathode is connected to ground and not the other way round. Inside the plastic bubble are two tiny bits of metal. The larger one is the cathode. Does it light? If not, the LED is faulty or the resistor is too high.
Reconnect the LED to pin 8, which is physical pin #14. (In case you got confused and used physical pin 8, no harm was done - physical pin 8 is another ground!) Reduce the delay times to 1 second on, 1 second off. Again be sure to connect its cathode side to ground. Does it blink? If not, perhaps Arduino's pin 8 driver is faulty.
Try the same thing on a different pin (adjusting your code, of course). If it still doesn't blink, there is probably an issue with either the MCU chip or the power you're supplying to it. Assuming you used the board's +5v and ground in test (1.), then the power is OK and the chip is likely the cause.


Arduino UNO with LMT86LP temperature sensor

The result from analogRead() is in counts of full scale, not in volts. Since you are using a 10-bit ADC, full scale is 1024.

1.8V/5V⋅1024=368.64


Hex String -> Byte Array -> Serial Write

What your code is aiming at isn't particularly clear to me, but I will assume that for some obscure reason you want to accept an input String containing a series of ASCII-encoded hex digits, and create an array of half that many bytes with reconstituted byte values.

First, here are several criticisms of the code shown.

It's likely length(input) won't compile but that input.length() will.

The expression input.substring((2*i),(2*i)+1)) is a String of one character.  If you want two characters, use input.substring((2*i),(2*i)+2)).  And use i += 2 instead of i++ in the for loop.

I don't understand String CMD = CMD+ISS.  I won't say it's invalid, as I don't know without more research.  But it looks like it's declaring variable CMD and using CMD in the initialization of CMD.  [In the example code I give below, I assume CMD should begin as an empty string and be filled up with reconstituted bytes.]

RS485Serial.write(input); // Send byte to Remote Arduino looks mis-commented; presumably it will write out all of the input, not just a byte.

Using a timed delay for holding RS485 Transmit open, as in
delay(10);
 digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
may cause problems.  On the one hand, it may usually waste five to ten milliseconds of time; on the other, it might occasionally disable RS485 transmit before transmission finishes.  Instead, look for a flag to test for transmission complete, or look for a buffer-fill count, or compute how long to wait, etc.

The next paragraph describes some reasons that Strings may perform badly in this sketch.  For additional discussion of Arduino String objects, see arduino.cc's String page, and see Majenko's The Evils of Arduino Strings page.

Each of the String-object operations in the code creates a new String.  New String objects SubS and CMD are created and destroyed in each pass of the for loop.  The object headers (with type data and member variables, such as a buffer pointer and buffer size) can be stack-allocated, which is harmless (does not leak or fragment memory) but takes some time.  Each String object's character-buffer is heap-allocated: see code in cores/arduino/ file WString.cpp.  Heap fragmentation can and will occur.  ... In brief:  In this application where using String objects is clunky and in the way, you might as well use ordinary C strings instead of String objects.

Ok, with criticisms out of the way, here's some example code that converts ASCII-encoded hex digits into a command string.  Note, as I don't know the specs for RS485Serial.write() or how it determines how much to send, for demonstration purposes I've supposed it can handle a C string.

// Function declaration for dehex()
byte dehex(char c); // Get nibble value 0...15 from character c

void SendCTRL (String input) {
  const char *hin = input.c_str();  // Get character array
  int clen = input.length/2;
  // Next line invalid in C++, ok in C99.  Probably need to
  // instead declare a fixed-length array, cmd[MAXCMDLEN], etc
  char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2) {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  RS485Serial.write(cmd);   // Send string someplace
  delay(clen/4);        // Wait for write to complete? What rate?
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

byte dehex(char c) { // Get nibble value 0...15 from character c
  // Treat digit if c<'A', else letter
  return c<'A'? c & 0xF : 9 + (c & 0xF);
  // Above assumes that c is a 'hex digit' in 0...9, A or a ... F or f.
  // It would make more sense to just use 16 consecutive characters,
  // like eg 0123456789:;<=>? or @ABCDEFGHIJKLMNO so the above
  // could just say `return c & 0xF;`
}

Edit 2:

The first statement, byte dehex(char c); is a function declaration for the dehex() function.  It tells the C/C++ compiler the datatypes that the function accepts and returns.  Note, instead of a function declaration at that point, one could instead put the function definition itself (which in the above follows SendCTRL(), a dehex() caller that needs to know dehex()'s datatypes).  Some versions of the Arduino IDE appear to work ok without function declarations ahead of use, but almost all other C/C++ environments will not.
In this edit I added const before char *hin = input.c_str(); because ATE-ENGE reports  “char *hin =input.c_str() is giving me an invalid conversion error from const char* to char*”.  That error indicates the left-hand-side variable has a datatype different from that of the right-hand-side expression and an automatic conversion isn't available.  Note, unfortunately the arduino.cc c_str() webpage doesn't specify the return type of c_str().

Edit 3:  Changed for (int i=0; i < clen; i+=2) to for (int i=0; i < 2*clen; i+=2) per notes in another question's answer.

Edit 4:  Changed cmd[i/2] = dehex(hin[i])<<4 + dehex(hin[i+1]) to  cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]) to avoid an operator precedence problem.  The precedence of +, addition, is higher than that of <<, bitwise shift, which in turn is higher than that of |, bitwise OR.  The unparenthesized expression with + adds 4 to dehex(hin[i+1]) and uses the total as a shift count; not at all as desired.  Note, one can of course use parentheses to control the problem, as in the expression (dehex(hin[i])<<4) + dehex(hin[i+1])


Well suppose you have a starting position, let's say 0 degrees, then once you detect and angle change, let's say 10 degrees, you know that there is a tilt of 10 degrees on one of the 3 axies.

The MPU6050 is a 6DOF, meaning 6 Degrees Of Freedom. This means that it can detect acceleration on axis: x, y, and z and it can detect gyro angles on axis: yaw, pitch, and roll.

For the best accuracy, use a mix of both acceleration and the gyroscope. This is the best way to calculate position. Heck, the Apollo space program used a gyro and accelerometer to navigate from planet Earth to the Moon.


Blinking cursor on Arduino is inconsistent and misses inputs

I don't have the hardware to test but, it should be more or less like this;
(I have also normalized the code into several functions for better readability.)

#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
#include <Time.h>
#include <TimeLib.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

unsigned long timerBlink; //Required for periodic blinking
int intervalBlink = 100;

void setup() {
    lcd.begin(16, 2);
    setTime(12, 30, 15, 0, 0, 0);
    timerBlink = 0;
}
int col = 0;

void loop() {
    readButtons();
    printDate();
    if (millis() - timerBlink > intervalBlink) {
        blink();
    }
}

void readButtons() {
    uint8_t buttons = lcd.readButtons(); //create readable buttons
    if (buttons) {
        lcd.clear();
        if (buttons & BUTTON_RIGHT) {
            col += 1;
        }
        if (buttons & BUTTON_LEFT) {
            col -= 1;
        }
    } //buttons
}

void blink() {
    lcd.setCursor(col, 0);
    lcd.blink();
    timerBlink = millis();//Start timer for intervalBlink
}

void printDate() {
    char time_out[16];
    lcd.setCursor(0, 0);
    sprintf(time_out, "%02u:%02u:%02u", hour(), minute(), second());
    lcd.print(time_out);
}

Instead of blocking delay function, using timeout with timestamp is a better practice.


My Leonardo, which I leave on all the time, is not hot. The CPU chip feels at room temperature as far as I can tell. If you were powering something from it, maybe you are drawing too much current. If it gets hot just sitting there doing nothing, and with nothing connected, something is wrong.

Maybe you damaged it in the past? Maybe hooked up some LEDs without current-limiting resistors? If not, it sounds like a faulty device to me.


You will get varying values on each read. A pin’s input is said to be floating if nothing is connected, which in simple terms can be explained as it just acting as an antenna for whatever electric noise is present in your environment. Its state is unknown, and utterly meaningless. If you hold a spinning electric motor close to the pin, you can see the values rise and fall more clearly.

Use a high value (10K or more) pull-down or pull-up resistor to partially mitigate this jitter. A pull-down would bring the read value down to around 0, and a pull-up would bring it up to around 1023.

Furthermore, it’s a good idea to always smoothen out analogRead (5-10 reads, ~25-50ms apart, average the values out) to get a good reading if precision is important. This is especially valid if you use longer wires, have an unshielded case, or use a switched mode power supply. Twisting the wires (GND and wiper IIRC, otherwise correct me) to a potentiometer helps.

Edit: You can use pinMode( A0, INPUT_PULLUP ); - it provides a 20-50Kohm pull-up, though I don’t trust this and always use 1/4W resistors instead. It saves space though, and is quite handy.


Getting "avrdude:stk500_recv(): programmer is not responding" while uploading sketch to Arduino Pro Mini

rx -> tx
tx -> rx

Please check your connections.


Alright so I figured it out. Thanks to user Butters for pointing me in the right direction.

The Arduino Uno DOES NOT have enough power to handle the ESP8266 itself. It needs a power source using a 5v to 3v stepdown chip. The 3v3 rail doesn't handle it by itself.