turning positional servo motor more then 180 degrees

First some basics to clear definitions:
A Servo Motor does not normally spin a full 360 degree rotation. Instead it is limited to a range of 180, 270 or 90 degrees depending on the make or type. A control signal is sent to the servo to position the shaft at the desired angle.

Conventional Servo Motor Timing

In a conventional analog servo motor a PWM signal with a period of 20 ms is used to control the motors. A signal of 20 ms has a frequency of 50 Hz.

The width of the pulse is varied between 1 and 2 ms to control the motor shaft position.

A pulse width of 1.5ms will cause the servo shaft to rest in the 90 degree position, the center of its travel.
A pulse width of 1ms will cause the servo shaft to rest at the 0 degree position.
A pulse width of 2ms will cause the servo shaft to rest in the 180 degree position.

Varying the pulse width between 1ms and 2ms will move the servo shaft through the full 180 degrees of its travel. You can bring it to rest at any angle you desire by adjusting the pulse width accordingly.

So if your servo is a 270 degree servo (like the domanrc DM-S0903MD or DS3218 270 Degree Digital RC Servo) the standard sweep sketch (Arduino Servo library) will let your servo sweep from 0-270 even if in the *.ino its myservo.write(180); So to simply test you could use write(map(desired_angle, 0, 270, 0, 180))
If you want to control it more precicly you use microseconds.

servo.attach(5,500,2500)
servo.writeMicroseconds(1500);

AND you have to use an extra power supply for 270 degree servos, the 5V from Arduino want make them move or only in a jittering way of.
If you just have a "defect" 180 degree servo turning to lets say 190 degree for some reason, you might try the microsecond method playing around with the values in attach, also use an extra power supply, but for real over 180 degree action get a 270 degree servo.


Using the physical serial port on a BSFrance LoRa32u4?

[ATmega32U4-based boards use] Serial1 to communicate via TTL (5V) serial on pins 0 (RX) and 1 (TX). Serial is reserved for USB CDC communication. For more information, refer to the Leonardo getting started page and hardware page.


It is possible you have too many resistors on the RS485 bus. From the RS485 wikipedia page there is this quote:

  Ideally, the two ends of the cable will have a termination resistor
  connected across the two wires.

This may explain why you can use 2 of your RS485 interfaces but not 3.  Consider removing the resistors from the RS485 board in the middle if possible.


Connecting an ESP8266 to WiFi without hardcoding the credentials

The common way to do this is to put the ESP8266 into AP (Access Point) mode and then serve a web page with the configuration interface.

To make it even easier, you can create a captive portal so that the user doesn't need to open a specific IP address in their browser. The captive portal will cause the configuration page to be loaded no matter what address they open.

A popular Arduino library that makes this all very easy is WiFiManager:

https://github.com/tzapu/WiFiManager


Thanks to the help from @Majenko♦ I was able to fix the issue.
1 - int sensorStatus; should have been set to static int sensorStatus = HIGH; to make the program remember the value of the sensor.
2 - sensorStatus = HIGH; should have been right after digitalWrite(relayControl1_1, HIGH); in the buttonStatus conditional else part to make the program set the sensorStatus back to HIGH correctly.
3 - Unrelated to the question posted, doing the above steps made the program run the motors continuously unless they were stopped by an obstacle from the IR sensor. This was fixed by adding delay(2000); digitalWrite(relayControl1_1, LOW); after the sensorStatus = HIGH; mentioned in the 2nd step.
Source Code after fixing:
const int relayControl1_2 = 12; // relay 1 of 2 (input 2)
const int relayControl2_1 = 11; // relay 2 of 1 (input 3)
const int relayControl2_2 = 10; // relay 2 of 2 (input 4)

const int inButton1 = 9; //input button 1
const int inButton2 = 8; //input button 2

int buttonStatus1 = 0;
int buttonStatus2 = 0;

const int inSensor = 7;

void setup() {
  Serial.begin(9600);
  pinMode(relayControl1_1, OUTPUT);
  pinMode(relayControl1_2, OUTPUT);
  pinMode(relayControl2_1, OUTPUT);
  pinMode(relayControl2_2, OUTPUT);

  pinMode(inButton1, INPUT_PULLUP);
  pinMode(inButton2, INPUT_PULLUP);

  pinMode(inSensor, INPUT_PULLUP);

}

void loop() {

  static int sensorStatus = HIGH;

  if (digitalRead(inSensor) == LOW) {
    sensorStatus = LOW;
  }

  if(sensorStatus == LOW) {
      buttonStatus1 = digitalRead(inButton1);

      if(buttonStatus1 == HIGH) {
        digitalWrite(relayControl1_1, LOW);
      } else {
        digitalWrite(relayControl1_1, HIGH);
        sensorStatus = HIGH;
        delay(2000);
        digitalWrite(relayControl1_1, LOW);
      }

      buttonStatus2 = digitalRead(inButton2);

      if(buttonStatus2 == HIGH) {
        digitalWrite(relayControl2_1, LOW);
      } else {
        digitalWrite(relayControl2_1, HIGH);
        sensorStatus = HIGH;
        delay(2000);
        digitalWrite(relayControl2_1, LOW);
      }
   }
}


send and recieve analog data from one arduino to another arduino via web/ethernet

ADC input has 100Mohm impedance. By placing C4 the signal at the ADC input has no DC path, is just floating between -0.7v and 5.7v , limited only by the input clamping diodes.
ADC can convert only voltages between 0 and the voltage reference, I suppose you use the default 5V reference.
But your signal is floating, and the ADC will cut any peaks outside of the conversion area giving the noise you hear.
Another issue I see here is that the data sheet of LM386 specifies a load between 4ohm and 32ohm. There is no warrantee that it will work without a load as in your case. Most likely not.
So you might want to connect C4 to a proper load and take the signal for ADC straight from pin 5 of LM386 which is auto balanced at half of the voltage supply.

simulate this circuit – Schematic created using CircuitLab
Later edit after I found the source of the schematic, there are also comments there that the schematic will never work with Arduino with the capacitor connected, the only working application was a sound detector where the signal distortion does not matter.
Please do not trust the content of any unknown website published by an anonymous just because it looks like a tutorial made by somebody who knows something.
Edit to add some info on how to debug the issue.
First, in the above schematic replace the resistor with a speaker and see if the sound is good. If not than see what is wrong with your amplifier.
If it's good and loud without any distortion then put the resistor back.
Use a binary mode serial monitor like Realterm to see how your data looks, the Arduino serial monitor works only in Ascii mode which turns a byte into three ascii chars which is slow.
Something like that
void setup() {
    Serial.begin(230400); // opens serial port, sets data rate to or maximum supported by your board to minimize latency
}

void loop()
   {
     unsigned int temp;
     temp = analogRead(0);
     temp = temp>>4; //strip low bits to fit in a single byte
     Serial.write(temp);
   }

Then see how your data looks, if you have to many 00 or to many FF than you know that your data us upper or lower limited or what is wrong with your signal.
I hope you are aware that the ADC conversion takes 100us and the wire transmission also around 200us the maximum sample rate you can expect is around 3khz and a maximum bandwidth of the audio signal of 1.5kHz which is half of the telephony bandwidth, you might want to use a faster DAC and use some non blocking ADC reading to use the time while ADC is working like in this article


How to flash the "atmega328" with AVRDUDE?

This seems to be quite a common problem, and there are a number of problems, each with their own solution.

Make sure you have selected the right chip
Make sure you have selected the right serial port (when you unplug your board, it should disappear).
Make sure you do not have anything plugged in to the tx & rx pins (usually 0 and 1).
Make sure your Atmega chip has a bootloader on it
Try another cable
There may be a problem with your computer - try another computer
If using another helps, try reinstalling the USB serial driver
Try unplugging the Arduino board, holding down the reset switch, then plugging it in (still holding down reset); continue to hold down reset for about 5 seconds.
make sure nothing else is trying to use your serial port
Does your chip have a bootloader? Chips bought as part of an Arduino will, otherwise, it almost certainly doesn't, unless it specifically says (in the description of what you bought).

If it does not have a bootloader (or may not have a bootloader) you will need to set this up. You can either use the instructions here: https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard (which I never got working) or you can use an ICSP like the http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VlIY_2xifXs (which is what I use) - works great. They can be had for a few dollars from China.


UART Software Serial - Syncing two sensors to make a tx and rx beacon

theyre roughly 15 cm apart

15cm substantially less than the time it takes to send the second device its command at 9600 baud (2 bytes, probably 20 bits counting framing, around 72 cm)

As a result you are likely missing the pulse, and perhaps catching some timeout, or even a cached response string from a next-to previous command which measured the previous pulse, including the time between pulses.

To operate that close, you will need to either use dedicated trigger/detect wires, or start the receiver before you transmit and try to subtract the delay from the time you started the receiver until the time when you transmit.

Beware that usage of software serial, as well as buffering of serial in general may introduce variable latency in your timestamping of the serial communications.  Ideally for something like this you would use a non-buffered implementation - the timing of serial data itself is potentially precise to a fraction of the baud rate, though we don't know how it is implemented on the sensor end.


All the differences between Arduinos: Pro Mini & Pro Micro

It is more the differences between ATMega328P + FTDI (Pro Mini) vs ATMega32u4 (Pro Micro)

Apart from the minor pin differences, the peripherals for both MCUs are the same. The major difference is the ATMega32u4 has built in full-speed USB. This allows the board to function as a USB device by implementing the appropriate USB stack. E.g. it can act as a

USB to serial converter (CDC device)
Keyboard or mouse (HID device)
USB hard drive (MSC device)
MIDI controller
and more...

The LUFA library from AVR devices can be used for this but means going outside of the Arduino IDE and compiling proper C code using the latest avr-gcc tools.

The Arduino core library has built-in support for the HID and CDC device profiles. The CDC profile is used for comms with the Leonardo, Micro, etc. while the HID profile is used for keyboard / mouse emulation.

The Leonardo / Micro boot loader implements a CDC profile for communications with the PC. This CDC profile uses Arduino vendor and product ids so unlike FTDI devices, requires an extra step to install an *.inf file on Windows.

You would have to recompile the Pro Mini bootloader for the Micro, but even then it would require an FTDI board as programming would need to be done via the TX and RX UART pins. If you we going to go to all that trouble you could just recompile the proper boot loader to have a shorter time out. Why is difference of 1 or 2 seconds in boot loader time important?

The ATMega32u4 uses more power than the ATMega328P.


Arduino Uno - External Power not working properly

The only difference between powering from USB and powering through the barrel jack is the voltage is reduced to 5V through a Low Dropout (LDO) voltage regulator. These are typically a clone of the popular LM1113-50 and vary in current handling capacity from around 500mA up to 1A.

I notice your board is not a genuine Arduino - therefore the components used may be at the cheaper end. So we'll assume a low-grade LDO that only handles 500mA before going into thermal shutdown with good heatsinking. Since there isn't on these boards we shall therefore assume a maximum of 400mA before it gets too hot. Probably somewhat conservative.

So if your entire circuit is drawing more than about 400mA you can expect the regulator to shut down, or at least to reduce the current and/or voltage available.

The fact you're seeing 4.8V rather than 5V could be an indication that there is voltage droop occurring - i.e., the regulator is not able to supply enough current so the voltage drops. This would be accompanied by the regulator getting very hot.

The regulator is the device with 3 pins on the right side and a single tab on the left directly above the barrel jack socket. See how hot that is getting.

As a rule of thumb if you can hold your finger on it without crying for 10 seconds it's not too hot.

Another thing you can do is to reduce your circuit to the bare minimum. Unplug absolutely everything and upload the Blink example sketch. Power that from the external DC and see if the LED blinks for you. If it does then the power supply is working OK. You can then add your peripherals one at a time to see when it fails.

If it doesn't blink then there must be something inherently wrong with the supply.

One possibility is that the LDO is oscillating due to insufficient or incorrect input and output capacitors. This basically means the "5V" voltage it gives out is actually wildly swinging between say 4.5V and 5V or 4.75V and 5.25V, which really confuses the microcontroller. Cheap LDOs are often more sensitive to the capacitors they are paired with and can suffer from this kind of problem.

To diagnose that kind of thing you would really need access to an oscilloscope to analyse the voltage.

If it is oscillating a 10µF ceramic capacitor connected between the lower two pins of the LDO (as orientated in your picture - that is Vout and GND) may cure it. A 1206 surface mount capacitor fits nicely across those pins and is reasonably easy to hand solder. You could also try a through-hole capacitor (ceramic again) between 5V and GND on the power header, but you really want it as close to the LDO as you can get it, so soldered direct to the LDO's pins is best.


Button debounce using millis() in this example

You've declared the variable for the millis function inside your loop correct and you've declared the delay duration you want to use. Two things you've missed are you've declared 2 variables with the millis function and to use it to control the program flow based on some condition to execute some code, in your case, to press 2 buttons to turn on and off an LED.

The way to to this is to use an if-else statement inside the loop function with one variable declared with the millis function, delay_duration as your reference, and 1 variable declared with a zero value.

unsigned long storeMillis = 0;
const int delay_duration = 500;

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

void loop() {
unsigned long currentMillis = millis();
if (currentMillis - storeMillis > 500) {
storeMillis = currentMillis; //update and store the value of storeMillis for the next iteration
//code you want to do
}


Find RSSI of Mobile Device Without Connecting

You have two questions, but what makes you think you can't find these out?

When you want to know what a device can do (and thus can't do) you should check the devices' datasheet. I believe it is this file.

Bluetooth (and gsm) devices often work by sending AT commands. For example: "AT+PIO" to set/query GPIO pins of the module.
You can send "AT+RSSI?" to get a response on the RSSI value.

Not everything can be mentioned in the datasheet though. If you can't find any sources on it, it's most likely not a feature.

The only way to add a "validation function" within the bluetooth connection code, would be to re-write the firmware of the device.

But, you could:

Connect (with everyone using the right pin)
Check their RSSI
Disconnect if it doesn't match your criteria

I'm not sure if this module can have multiple connections, I didn't really see a way to disconnect a single connection. If not, you could even toggle the power to the module to "disconnect" the client(s).


Continuous servo speed control with Arduino Uno controller and servo shield

The speed of your servo is controlled by the pulswidth of a square wave signal. According to the datascheet of the servo the motor stops on a pulsewith of about 1500 µSec (+- 5 µSec).

From 1500 to 900 μSec the motor turns clock wise. And it getting faster with decreasing pulsewidth.

From 1500 to 2100 μSec the motor turns counter clock wise. And it getting faster with increasing pulsewidth.

Next we have to check whether your shield and the library can handle that values and which value you have to give to the servo[i].write(?) function. I can read cyrillic but I do not understand russian good enough to read the f. manual. So I have to look into the code on GitHub (https://github.com/amperka/Multiservo/blob/master/library/Multiservo ).

Et voila:

Multiservo::attach(int pin, int minPulse, int maxPulse)

You can define the min and max pulseWidth, that's great. Let's do it:

#include <Multiservo.h>
#define SERVO_COUNT 2

Multiservo servo[SERVO_COUNT];
// speed is 0 ( full speed CW )
int speed = 0;

void setup(void)
{
  for (int i = 0; i < SERVO_COUNT; ++i)
  {
    servo[i].attach( i, 900, 2100);
    // 900 - 2100 is mapped from 0 to 180
    // so 90 is the middle where the motor stopps
    // 180 the motor runs as fast as possible CCW
    // 0 the motor runs as fast as possible CW
    servo[i].write( speed );
  }
}

void loop(void)
{
   // Here I halt the program if the motor stops.
   // If you use a lower value than 89 you can halt the program
   // at the corresponding speed. If you use a higher value instead of 89
   // the motor starts rotating counter clockwise.
   // Do not use a value greater then 179 or less than 1.
   if ( ++speed > 89 ) speed = 90;

   servo[1].write( speed );
   servo[2].write( speed );

   delay(25);
}

Ah, of cause I have not hte hardware, so I can not test the program. Use it as an example.


Controlling keyboard LEDs with USB Host Shield

There does seem to be a method called SetReport in the USBHID class, which looks like it takes the same arguments, which I'm trying to use.

The method arguments of the new SetReport() method aren't quite the same and some are in a different order.
The old method signature was:
uint8_t setReport( uint8_t addr, uint8_t ep, unsigned int nbytes, uint8_t interface, uint8_t report_type, uint8_t report_id, uint8_t* dataptr );

...while the new one is:
uint8_t SetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr);

It seems to me the equivalent call would be:
usbhid.SetReport( 0, KBD_IF, 0x02, 0, 1, &leds );


Arduino String: use a non-null-terminated char array?

Assuming you are talking about the function

bool painlessMesh::sendBroadcast( String &msg, bool includeSelf = false)

Then you'll see that ultimately, the library passes msg into the function buildMeshPackage where it constructs a JSON message (see here)

String ICACHE_FLASH_ATTR painlessMesh::buildMeshPackage(uint32_t destId, uint32_t fromId, meshPackageType type, String &msg) {
    debugMsg(GENERAL, "In buildMeshPackage(): msg=%s\n", msg.c_str());

    DynamicJsonBuffer jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["dest"] = destId;
    //root["from"] = _nodeId;
    root["from"] = fromId;
    root["type"] = (uint8_t)type;

    switch (type) {
    case NODE_SYNC_REQUEST:
    case NODE_SYNC_REPLY:
    {
        JsonArray& subs = jsonBuffer.parseArray(msg);
        if (!subs.success()) {
            debugMsg(GENERAL, "buildMeshPackage(): subs = jsonBuffer.parseArray( msg ) failed!");
        }
        root["subs"] = subs;
        break;
    }
    case TIME_SYNC:
        root["msg"] = jsonBuffer.parseObject(msg);
        break;
    default:
        root["msg"] = msg;
    }

    String ret;
    root.printTo(ret);
    return ret;
}

Even if you did construct a String with null terminators in it, the moment it gets put into the JSON string it destroys everything. JSON by default doesn't support binary data strings (reference).

So, the library is a problem because it happily passes data as JSON messages, and that's bad if you want binary data transported. You could use Base64 or the more efficient http://base91.sourceforge.net/ encoding though to mitigate this a little bit, or search for a different lib.


If you know the interval between heart beats, you can calculate the frequency using the formula: frequency = 1 / time. Now if you take the frequency and multiply it by 60, you should get BPM.

I don't have one of the sensors you are using so I connected a potentiometer to pin A0 to test this code.

    int UpperThreshold = 518;
    int LowerThreshold = 490;
    int reading = 0;
    float BPM = 0.0;
    bool IgnoreReading = false;
    bool FirstPulseDetected = false;
    unsigned long FirstPulseTime = 0;
    unsigned long SecondPulseTime = 0;
    unsigned long PulseInterval = 0;

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

    void loop(){

      reading = analogRead(0);

      // Heart beat leading edge detected.
      if(reading > UpperThreshold && IgnoreReading == false){
        if(FirstPulseDetected == false){
          FirstPulseTime = millis();
          FirstPulseDetected = true;
        }
        else{
          SecondPulseTime = millis();
          PulseInterval = SecondPulseTime - FirstPulseTime;
          FirstPulseTime = SecondPulseTime;
        }
        IgnoreReading = true;
      }

      // Heart beat trailing edge detected.
      if(reading < LowerThreshold){
        IgnoreReading = false;
      }

      BPM = (1.0/PulseInterval) * 60.0 * 1000;

      Serial.print(reading);
      Serial.print("\t");
      Serial.print(PulseInterval);
      Serial.print("\t");
      Serial.print(BPM);
      Serial.println(" BPM");
      Serial.flush();

      // Please don't use delay() - this is just for testing purposes.
      delay(50);
    }

Updated answer in response to your comments below:

The sketch is reading the data and sending the data to the serial monitor every 50ms because of the delay(50). What if we changed that to 1000 ms? The serial monitor would update once per second which would be more "human readable". The problem with that idea is for heart rates faster than 60 BPM, the reading would be inaccurate. I don't have a sensor to test with but I'm guessing a 1 second delay would make the code inoperable.

Before we add more complexity to this sketch we really should get rid of that delay. It would be nice to have one "timer" that we could use to update the BPM calculation and a second "timer" to update the serial monitor every second, or half second, or what ever you want it to be.

We can do that without any libraries using millis(). Here is an updated sketch using millis() for timers. This sketch has the blinking of the on board LED added to it. I'm using an Uno so you'll have to change LED_BUILTIN to what ever pin number you are using.

int UpperThreshold = 518;
int LowerThreshold = 490;
int reading = 0;
float BPM = 0.0;
bool IgnoreReading = false;
bool FirstPulseDetected = false;
unsigned long FirstPulseTime = 0;
unsigned long SecondPulseTime = 0;
unsigned long PulseInterval = 0;
const unsigned long delayTime = 10;
const unsigned long delayTime2 = 1000;
const unsigned long baudRate = 9600;
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;

void setup(){
  Serial.begin(baudRate);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop(){

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

  // First event
  if(myTimer1(delayTime, currentMillis) == 1){

    reading = analogRead(0);

    // Heart beat leading edge detected.
    if(reading > UpperThreshold && IgnoreReading == false){
      if(FirstPulseDetected == false){
        FirstPulseTime = millis();
        FirstPulseDetected = true;
      }
      else{
        SecondPulseTime = millis();
        PulseInterval = SecondPulseTime - FirstPulseTime;
        FirstPulseTime = SecondPulseTime;
      }
      IgnoreReading = true;
      digitalWrite(LED_BUILTIN, HIGH);
    }

    // Heart beat trailing edge detected.
    if(reading < LowerThreshold && IgnoreReading == true){
      IgnoreReading = false;
      digitalWrite(LED_BUILTIN, LOW);
    }

    // Calculate Beats Per Minute.
    BPM = (1.0/PulseInterval) * 60.0 * 1000;
  }

  // Second event
  if(myTimer2(delayTime2, currentMillis) == 1){
    Serial.print(reading);
    Serial.print("\t");
    Serial.print(PulseInterval);
    Serial.print("\t");
    Serial.print(BPM);
    Serial.println(" BPM");
    Serial.flush();
  }
}

// First event timer
int myTimer1(long delayTime, long currentMillis){
  if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
  else{return 0;}
}

// Second event timer
int myTimer2(long delayTime2, long currentMillis){
  if(currentMillis - previousMillis2 >= delayTime2){previousMillis2 = currentMillis;return 1;}
  else{return 0;}
}

The code compile size with delay is 4,732 vs the millis timers at 4,682 (with the LED code removed). Two timers for less than the price of one delay :)

The LED will remain on for the duration of the heart beat reading above the LowerThreshold. If you want to have it on longer or decide how long it should be on for, I won't write the code for you but I will give you a hint. You can copy myTimer1() again and make a third timer.


Pre-heat time required for MQ-5 gas sensor

Please be clear when you mean the one time only pre-heat and when you mean turning the sensor on to take a measurement.

It is a electrochemical sensor and it needs time to burn-in. During those 24 hours, the impedance of the sensor changes a lot. After those 24 hours it can be used in a normal way and it will return consistant values.

The pre-heat should be done just once. I mean: just once in the lifespan of the sensor. After buying it, you should run the pre-heat.
When the manufacturer writes in the datasheet that the pre-heat time is 24 hours, then you should do 24 hours.
I suggest to connect the sensor in a normal way, with 'A' en 'B' pins connected and with the load resistor, and keep it on for 24 hours. Maybe it is already stable after a few hours, but keep it on for 24 hours to be sure.

To take a measurement, the sensor needs time to warm up. About 5 minutes might be okay. I think that 2 minutes is definitely too short.
When the sensor is always at room temperature, and the time to warm up is always the same, then the measurement is relative accurate and can be compared with other measurements. That means that when the sensor is mostly turned off to save power, only a few minutes to warm up can be used. However, I would start with at least 5 minutes.

[EDIT] The datasheets and other information from the manufacturers use the term "pre-heat" in different ways. The Technical Note in the link by @EnricBlanco uses the term "preheating" only for the "one-time-only" heating after storage to make the sensor more stable, as far as I can tell. Although it is not "one-time-only", it should be applied after storage or changing conditions as well. @EnricBlanco, try a very cheap MQ gas sensor (which is probably not preheated in the factory) and see how the impedance changes a lot during the first hours of preheating, and becomes stable after a few hours.


Why does Arduino Tone example with 8 ohm speaker make USB port fail?

As already mentioned in your question, in the Arduino tutorial "Melody" under "Hardware Required" is stated "piezo buzzer or a speaker" and in the comment that heads the sketch is stated: "8 ohm speaker on digital pin 8". But the pictures under "Circuit" and "Schematic" show a piezo sound transducer.

In any case the word "buzzer" is wrong. A buzzer usually has a built-in oscillating circuit or mechanism and, when energized, produces sound at a more or less fixed frequency. Better would have been: a piezo speaker and a 'normal' (moving coil) speaker.

There is a big difference between a piezo and a speaker: under a dc-voltage the piezeo wil have a near infinitive resistance and the 8 Ohm speaker roughly 4 Ohms. At 400 Hz the piezo has an impedance of roughly 2000 Ohm (there is a huge range of piezo's with varying characteristics), while the impedance of the normal speaker will be roughly 10 Ohm.

One side of the buzzer/speaker is connected to Ground, therefore current is only flowing when the side connected to pin 8 is HIGH (pin 8, has to source the current and not to sink it).

The datasheet of the Atmega328P states at page 299 that the absolute maximum ratings (which is not the same as maximum allowable operational ratings) are 40 mA for an I/O-pin is 40.0 mA and 200 mA for Vcc and Ground pins.
The datasheet shows a graph (fig. 35-24 at page 600) showing "I/O Pin Output Voltage vs. Source Current (VCC = 5 V)". From this graph an internal resistance of about 26 Ohm can be derived. The graph does'n show what happens at pin-currents larger than 20 mA, but let's guess the internal resistance stays about the same 26 Ohm.

When pin 8 is constantly HIGH (5 V at 0 Hz) the current through the speaker would be about 5/(26+4) = 167 mA. This is far above the 40 mA maximum rating for the pin current, but not enough to trip the USB-fuse (trips at 500 mA). When this situation lasts the pin-driver will be destroyed. This could cause an internal open circuit (with no further consequences) or an internal short circuit which might cause a supply current higher than 500 mA which would trip the USB-fuse. In this case pin 8 would be permanently destroyed which is easy to establish. If pin 8 keeps working, this scenario doesn't happen.

Normally the sketch "Melody" would not output a dc-signal (0 Hz). At 400 Hz the pin current would be 5/(26+8)= 147 mA. This is still far above the maximum rating for the pin current and the scenario is the same as above.

So the only way the USB-fuse could be tripped is when the pin driver burns out and causes a short-circuit from Vcc to ground. Reading between the lines, my impression is that Raddevus tried this out more than once, which means that pin 8 keeps working. Also I don't think that it is likely that an burn-out of a (few) transistor(s) of an IC causes a short-circuit. Therefore the cause for tripping the USB-fuse must lie elsewhere.

A last consideration is that Raddevus mentions (in his comment of June 18 at 15:34) three input buttons which are not in the 'schematic' shown with his question. He also seems to use a dodgy board ("missed ground hole on bboard, hit 5v"). So may be we don't see all the factors involved.


Arduino with interrupts enters in a locking state

When the AVR processor goes to sleep, the only way it can wake up is
by an interrupt. If it goes to sleep with interrupts disabled, then it
will never wake up.
Interrupt routines are by default non-interruptible: the first thing the
processor does when servicing an interrupt is to disable further
interrupts. Your onAlarm() function is thus running with interrupts
disabled. If it goes to sleep, it will lock the processor.
A quick and dirty fix would be to call interrupts() right before going
to sleep. I would not recommend that though, as you will end up piling
interrupt contexts one over another. The proper fix would be to trim
down your interrupt  service routines to the bare minimum that must be
done immediately, and handle everything else in regular code, within
loop(). In this particular case, setting a volatile bool might well
be the only thing you really need to do. Your loop() would test that
bool and take care of everything else.


sleep_enable() allows the MCU to sleep, but it does not cause it to sleep. Call sleep_cpu() after enabling.


Check out the TemperatureWebPanel example: you'll see that you can make your own REST APIs and pass any values your sketch can handle.


No code, but Fatal exception (0): epc1=0x402066ac, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000 in Serial Monitor

Three words.  "You Bricked it"
Before you go surfing on the web for days and days, I'm just going to say the module is bricked.  I've been there and found out that you should never use these devices on breadboards and with funky power sources.  There is this chip within the module called eFuse,  which is basically an electronic fuse that's really easy to destroy.  Just use the Arduino YUN or other certified or Chinese clonable modules. Those Italians are smarter than you think. That's probably more reliable because you won't have any power issues or frying issues.

I'm also assuming that you are getting a fatal exception (0) in the Serial Monitor.  In that case, your module's death sentence is officially sealed.

Congrats. :(


The clue is in the error...

  too few arguments to function 'Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer, const char*)

You have defined the function as this:

Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

And yet you then try and call it like this:

onSignalSound();

Spot the mismatch?

I suspect you don't want to be calling that function there since it seems to be in a bit where the sound has already been started.


Why are Tone.cpp and IPAddress.cpp getting built for my project?

As stated the IDE's equivalent to the make will compile anything everything it can find, in scope. But its linker has eliminate garbage enabled, hence anything not called or not static will not be linked into the EXE.

You can "avr-objdump -t" to create a map from your elf. And -d for an assembly listing. As to see exactly what is in the EXE, for your self. You need to enable show verbose output of compilation from the IDE's preferences, to display the temporary directory that contains the elf file.

example:

C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp>C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -t MP3Shield_Library_Demo.cpp.elf > MP3Shield_Library_Demo_wo_mem.cpp.elf.map
C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp>C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -d MP3Shield_Library_Demo.cpp.elf > MP3Shield_Library_Demo_wo_mem.cpp.elf.lst

I did the above and commented out a call to a function member of my library, between subsequent builds. To see that the code was not linked into the assembly.


IDE compiles incorrect file after renaming them

The Arduino IDE does not monitor changes to open files. So if you rename or change a file externally (i.e. in another editor), the IDE won't update the file contents. Therefore, after such a change, a restart might be necessary.
Note: If you use another editor to change a file but only compile (and upload) in the IDE, this will work, because the compiler correctly reads the updated file. But editing the source in the IDE and an external editor at the same time might overwrite either change!


A non-blocking version is often needed as there is often other tasks to be performed during the wait. The "blink-without-delay"-pattern is a solution but unfortunately it becomes tedious to use with several time periods and logic.

The Timemark library helps abstract the pattern and hide a lot of the details. The below sketch uses two timemarks and a simple state-machine to help reduce complexity.

#include <Timemark.h>

Timemark turnOnWait(30000L);
Timemark turnOffWait(3000L);

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      turnOnWait.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (turnOnWait.expired()) {
      digitalWrite(pin, HIGH);
      turnOffWait.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (turnOffWait.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

Two timemarks are used for clarity. It is possible to use a single timemark and reinitiate it with a new time limit.

#include <Timemark.h>

const uint32_t TURN_ON_TIMEOUT = 30000L;
const uint32_t TURN_OFF_TIMEOUT = 3000L;

Timemark timemark;

enum {
  IDLE,
  TURN_ON_WAIT,
  TURN_OFF_WAIT
};
int state = IDLE;

const int pin = 4;
int control = 0;

void setup()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loop()
{
  ...
  switch (state) {
  case IDLE:
    if ((control > 100) && (control < 130)) {
      timemark.limitMillis(TURN_ON_TIMEOUT);
      timemark.start();
      state = TURN_ON_WAIT;
    }
    break;
  case TURN_ON_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, HIGH);
      timemark.limitMillis(TURN_OFF_TIMEOUT);
      timemark.start();
      state = TURN_OFF_WAIT;
    }
    break;
  case TURN_OFF_WAIT:
    if (timemark.expired()) {
      digitalWrite(pin, LOW);
      state = IDLE;
    }
    break;
  default:
    ;
  }
  ...
}

The Scheduler library allows the blocking version (delay) to be used. Non-blocking is achieved by context switching on yield() or delay(). Below is a rewrite using this style:

#include <Scheduler.h>

const int pin = 4;
int control = 0;

void setup()
{
  ...
  Scheduler.start(setupController, loopController);
}

void loop()
{
  ...
  delay(1000);
}

void setupController()
{
  ...
  pinMode(pin, OUTPUT);
  digitalWrite(pin, LOW);
}

void loopController()
{
  ...
  if ((control > 100) && (control < 130)) {
    delay(30000L);
    digitalWrite(pin, HIGH);
    delay(3000L);
    digitalWrite(pin, LOW);
  }
  else {
    delay(100);
  }
}

Cheers!


Updated Arduino IDE and Arduino not working

Allright, seems to be fixed. After a 3rd reinstall it seems like its fixed. I reinstalled the whole package, including the drivers, and now it seems to recognize the device again.

Also the compiling now stops properly when done and shows "upload complete".


"Sorry, my description was not clear enough. We want to measure everything in total AND every sensor separately. So, we do not really have to measure every sensor, it would be enough to have some reliable numbers to work with."

"it possible to measure the energy, say, for every pin on the Arduino?"

You ask if it possible to measure the energy- yes it is-or at least an approximation. The basic solution is as follows. Suppose you want to find the energy consumed by some component at one pin.  Energy is measure in joules. For an electrical circuit we the amount of energy (consumed in 1 second) is given by the formula

joules=current X voltage.
Lets consider the case with one sensor first , lets refer to this as sensor A.
The amount of energy that electrical component consumes in some time duration is by sensor A is:

joules (use by sensor A)=current X voltage X time duration sensor A is on

Now to make this formula applicable to your answer- we can replace voltage by the average voltage, and current by average current, since this is mathemtically equivalent, that the component is on for, and the time duration would be the time the component is on for. So the equivalent formula that can be used is

joules= average current X average voltage of sensor A during time duration X time duration sensor A is on

So for example if the sensor is only ever used for 50 minutes for all time throughout your project- and the sensor is turned on at the arduino pin for 1 second for every minute of that 50 minutes then the energy used by that sensor on that specific pin is equivalent to leaving the pin on for 50 seconds at the average voltage and average current of that sensor. Say the average voltage is 3v then the energy and average current is 20ma. Then the energy used by that sensor is thus
3v*0.02amps*55 seconds=3.3 joules.

Thus to get the total energy (if there were two sensors A and B) you would just need to sum

(joules (use by sensor A)= current of A X voltage of A Xtime duration sensor A is on)+(joules (use by sensor B)=current of B Xvoltage of B Xtime duration sensor B is on.)

Similar formula for more sensors.

To sum up- basically you would need your arduino program to keep track of how long each sensor pin is on (assuming high voltage turn on the sensor and makes it use power, low voltage turns off the sensor or make it use no power)  for each of the time duration in the formula for the duration of the project, you would need an estimate of the average voltage and current (e.g. from data sheet) or another way. Then you would need to use the formula in your code to compute the energy used by each sensor and the total energy.
If you have a way to measure the voltage and current fast enough then you could use them measurement instead of using average value as explained above-but I guess using averages is the easiest way to do it.

.


Serial loopback not working with jumper wires connected

I can not comment, it turns out that this example that you are working is not very suitable, since the RX and TX are directly connected to the USB connection (for Arduino UNO), that is, you can only use these pins as long as it is loaded from Sketch uses An external power supply to connect the Arduino, my recommendation is to work if you have a sensor to verify the transmission of data by serial port. Greetings


Need help understanding how RF communication works with 2 arduinos

Many questions so broad answers, but hopefully informative for your research

  What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?

It depends broadly on what you use. If you use an ethernet peripheral then the communications will be entire ethernet packets with whatever protocol stack you have above it in payload. For simple RF communication modules it may be as simple as a serial stream delivered 8 bits at a time. The simplest rf (buzzer-style) would simply interrupt (or drive a pin high) when the transmitter is sending a signal.

In Your case the transmitter uses an addressed protocol with a payload packet of between 1 and 25 Bytes of data. This means that you will need code to read and store the necessary payload, maintain configuration data and keep track of addresses of the other systems to message. You also need to poll (or handle interrupts from) the rf module to make sure there aren't messages from the transmit node.

How you convert the data is up to you, a string can be represented by a sequence of bytes and can be send and read as a string on the receivers end. Your rf module will deliver you data in 1-25 byte chunks, what you send in that chunk and how to encode it is entirely up to you.

On the low level,the way this module is configured, the MCU sends data into the rf ic using a serial protocol, the module incorporates a buffer to allow the MCU (slow - 8 bit) to send the data and not have to keep up with the 1Mbps throughput of the rf. On a physical level the signals of the chip look thus:

  My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?

Ping Pong is a game and not a well defined technical term. For precision you can define ping-pong as an echo where the transmitter effectively acknowledges the message by re-transmitting it back to you.

  Are RF units very different? Is this one particularly difficult?

RF units can be very different depending on what high level protocol they offer. This unit is somewhere half way between full blown wifi and simple and modulated RF communications. It gives you addressing and error correction as well as a robust communication scheme

This particular unit is made to be relatively "modern", it uses GFSK - a frequency modulation scheme -to transmit and receive data to uniquely addressable nodes on a number of channels. At 2.4 GHz it is high throughput, legal.  It is not the simplest toy.

In terms of simplicity, this module has a lot of examples and documentation, given that it has an arduino library it has a high likelihood of working and succeeding, but you will need to use more advanced microcontroller features to fully utilize the device (e.g. interrupts, DMA).

For other RF options there are lots of things to consider. Going up to wifi requires you to maintain a much more complex stack, meaning more processing power and code, if you want to offer TCP/IP services (say webserver) it is even more code but can be done on an 8 bit arduino. Going down to simpler protocol may win you less power and simpler code but a headache to expand.

  If I just want to send with one receive with the other shouldn't this simplify the code?

You will still need to implement both a receiving and a transmitting application so the work is still all there, it will simplify the higher level logic into separate application which is easier.

  What are pipes? How many can I open?

I see nothing about pipes from a cursory glance at the docs, perhaps you can illuminate more on what you are confused about?

In general pipes are a "hole" where an application (in the broadest sense) can stream data and it will be consumed by whoever is on the other end, a black hole of a serial data stream. You can implement a pipe as a high level software construct that will buffer and consume data from peripherals and wait to send it out the RF transmitter, it may also be implemented on a hardware level with discrete buffers and additional logic around the rf transmitter etc. As a conceptual element you can probably use a "pipe" concept for communication between the different devices in your code (e.g. move byte to pipe 1 for device 1, move byte to pipe 2 for device 2, let the "driver" handle order), this is a design paradigm that makes software development easier.

  If I have 3 or more of these what changes will I need to make to the code?

The rf module is fully capable of addressing up to 65,536 unique hosts, so the device is fully ready to talk to 3 of your hosts, however the software logic needs to track the addresses and other comms data about each host as well as process the data for them (if its different) in enough time.

If you are expecting this in advance, good design decisions early on (e.g. small API or library) will make this much easier on yourself to add features in the future.

Final Thought

If you need a simple echo, this may be a bit overkill for your system, however it is relatively powerful and may make it easier for you to program since you can work with "real-world" data units and send multiple byte packets easily.

I would highly recommend you read and understand the datasheet for the RF chip, be thankful that the nice library takes care of the messy details for you, but understanding how it works will certainly help you understand how to use it best.

An 8 bit Atmega may not be powerful enough to process and transmit 3 separate streams together (if they are identical its less difficult) if you require a constant high rate transmission or if you do a significant amount of processing on the arduino before sending you will feel the limitations of the chip and a 32 bit board may be worth looking at.


I2C Master send reset command to the slave counter

void receiveEvent (int howMany)
  {

  command = Wire.read ();  // remember command for when we get request
  //Serial.println(command);
  switch (command)
     {
     case CMD_WRITE_D2:
     Serial.println("comando 5 ricevuto");
     char cmdrst=Wire.read();
     delay(100);
     Serial.println (cmdrst);
     break;
    }
} // end of receiveEvent

Don't do serial prints inside an interrupt service routine (ISR). That is, not here.
Don't do delay inside an ISR.

  if (key !='A')
  {

I would be checking for NO_KEY first, otherwise you will assume that no key press is not 'A' and be doing that transmission to the slave a lot.


UART connection between Arduino Nano and NodeMCU

You can't connect the same Serial to a computer over USB and to a Nano at the same time. Not only because the Nano is on 5 V which disturbs the 3.3 V side of the USB converter.

Disconnect the NodeMCU from computer, try to power it from Nano's 3.3 V pin (not for WiFI) and don't forget to connect ground between the MCUs.

Nano has one Serial, which is connected over USB to computer too. So there too you can't use the USB and RX TX pins at the same time. You could use SoftwareSerial to connect to NodeMCU.

The Nano TX to esp8266 RX should have logic level conversion to not to send 5V to esp8266 3.3V pin.


LCD shows output without pressing the sensor

First off I edited indentation in your code because incorrect indentation is little bit confusing.

#include <LiquidCrystal.h>
LiquidCrystal lcd(13,12,11,10,9,8);
#define vibrate_sense 7

char str[70];
char *test="$GPGGA";
char logitude[10];
char latitude[10];

int i,j,k;
int temp;
//int Ctrl+z=26;    //for sending msg
int led = 13;

void setup(){
  lcd.begin(16,2);
  Serial.begin(4800);

  pinMode(vibrate_sense, INPUT);
  pinMode(led, OUTPUT);

  lcd.setCursor(0,0);
  lcd.print("..Initializing..");
  lcd.setCursor(0,1);
  lcd.print("....System...");
  delay(1000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Searching for");
  lcd.setCursor(0,1);
  lcd.print("Gps Signals");
  delay(2300);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Setup Completed");
  delay(500);
  lcd.setCursor(0,0);
  lcd.print("Accident detect");
  lcd.setCursor(0,1);
  lcd.print("& Alert system");
  delay(1500);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("No accident");
  lcd.setCursor(0,1);
  lcd.print("occured");
}

void loop(){
  if (digitalRead(vibrate_sense) == 0){
    for(i = 18; i < 27; i ++){          //extract latitude from string
      latitude[j]=str[i];
      j++;
    }

    for(i=30;i<40;i++){          //extract longitude from string
      logitude[k] = str[i];
      k++;
    }

    lcd.clear();
    lcd.setCursor(0,0);        //display latitude and longitude on 16X2 lcd display
    lcd.print("Latitude(N)");
    lcd.print(latitude);
    lcd.setCursor(0,1);
    lcd.print("Longitude(E)");
    lcd.print(logitude);
    delay(500);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Accident has");
    lcd.setCursor(0,1);
    lcd.print("been Detected");
    delay(500);
    lcd.clear();
    lcd.print("Sending SMS");
    delay(500);
    lcd.clear();
    Serial.begin(9600);

    Serial.println("AT+CMGF=1");    //select text mode
    delay(10);
    Serial.println("AT+CMGS=\"7066128969\"");  // enter receipent number
    Serial.println("Vehicle Accident occured:");
    Serial.print("Latitude(N): ");             //enter latitude in msg
    Serial.println(latitude);                  //enter latitude value in msg
    Serial.print("Longitude(E): ");            //enter Longitude in Msg
    Serial.println(logitude);                  //enter longitude value in msg
    Serial.print("http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=");
    Serial.println(latitude);
    Serial.println("+");
    Serial.println(logitude);
    Serial.write(26);                      //send msg  Ctrl+z=26

    lcd.setCursor(0,0);
    lcd.print("SMS Sent");
    delay(1000);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Help Please");

    temp = 0;
    i = 0;
    j = 0;
    k = 0;
    delay(20000);                        // next reading within 20 seconds
    Serial.begin(4800);
  }
}

void serialEvent(){
  while (Serial.available()){            //Serial incomming data from GPS
    char inChar = (char)Serial.read();
    str[i] = inChar;                    //store incomming data from GPS to temparary string str[]
    i++;
    if (i < 7){
      if(str[i-1] != test[i-1]){         //check for right string
        i = 0;
      }
    }
    if(i >= 60){
      break;
    }
  }
}

Second thing is this line if (digitalRead(vibrate_sense) == 0){ you are checking there vibrate_sense for value 0. Are you sure, that triggered value is 0 and not 1? Try this code to test which value is equal to triggered state.

#define vibrate_sense 7

void setup() {
  Serial.begin(9600);
  Serial.println("Sensor testing");
  pinMode(vibrate_sense, INPUT);

}

void loop() {
  Serial.println(digitalRead(vibrate_sense));
  delay(300);
}

Last thing is connection of your sensor/button. For button you have to use also PULL_UP/PULL_DOWN resistor to have correct logic value on digital pin.


How do I use ATTiny pin 5 (RESET) as a digital output?

RSTDISBL is bit 0 of the high fuse byte. Use avrdude to read the current value of the high fuse byte (-U hfuse:r:-:h), clear bit 0, and then write the value back out (-U hfuse:w:0xXX:m).


Powering Arduino through 12V USB communication unstable

12V is a little on the high end for what the arduino can handle by itself. If I were you I would use a DC step down Buck Converter module to hold the voltage at somewhere around 6v.

http://www.ebay.com/itm/like/400673913185?lpid=82&chn=ps

They're super cheap and pretty easy to use. Simply solder the + and - leads from your 12v power supply to the +in and -in on the buck converter. Then the + out and -out to the + and - for your arduino. Turn the potentiometer until you get somewhere around 6V.

Edit:

Actually I was just reading online, and some people have trouble communicating with the arduino through USB while an external power source is connected. Internet says this problem is related to sharing voltages.

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


Did you make sure the battery is charged? Does it have enough voltage to power the board? Remember that Arduino has internal voltage regulator, so you need something little more than 5V in order to get it working okay.

(Comment by bpinhosilva re-purposed as an answer so this will stop showing up as unanswered).

  @bpinhosilva you are right, the battery was not supplying enough power to make arduino work.

Please accept this so that the number of unanswered questions goes down. :)


ESP32 with Lolin 2.4 inch TFT Shield Power control

The backlight of this shield is ON as long as there's power on the 3.3V pin, unless you make GPIO 32 an output and pull it low.
In deep sleep, however, GPIO 32 will stop acting as a pulled down output pin but the esp32 keeps its 3.3V output pin powered, so the backlight will switch ON.
You could power the display over a mosfet, controlled by a GPIO.


How to write makefile-compatible sketches?

By gcc/g++ I think you're referring specifically to avr-gcc/avr-g++.  Your arduino code probably won't be considered valid C/C++ code because gcc will try to compile with your PC as the target system. Many of the Macros in "WProgram.h" will refer to inaccessible memory on your target system.

Providing you include the header file "WProgram.h" and you build your code with the Arduino Makefile above (which uses avr-g++ not g++), your cpp files should compile and link correctly.  Likewise, you will be able to open your Arduino code within the IDE and Verify your code there.  The IDE puts in the "WProgram.h" file for you, so technically it would be included twice.  However, the include guards will prevent any duplicate code from being compiled.


You should never do this:

Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

Yes, it should cope with it and append the strings, but that's really nasty even if it does work. And there is absolutely no call to ever do concatenation when printing to serial.

Instead just use:

Serial.print(takenKeybinds);
Serial.println(F("/64 Keybinds taken."));

Note also the use of the F() macro when printing a string literal. This keeps the string in flash and prevents it being copied to RAM, which is just wasteful.

The same with your big long string - it's wasting RAM, and if you never want to modify it, why have it in RAM? Better is:

Serial.println(F("What do you want to do? Type the following commands in this terminal:"));
Serial.println(F("new  --> Creates a new Keybinding"));
Serial.println(F("delete  --> Deletes a previous Keybind"));
Serial.println(F("lookup --> Find what is bound to a key"));
Serial.println();
Serial.println(F("Turn off the switch to go back to the normal mode."));


How to convert kitchen timer code into a countdown

As a start, you need to initalise the secondes and minutes variables to 30 and 1 respectively.
replace signed short minutes, secondes; with:
signed short minutes = 1;
signed short secondes = 30;

Next thing I notice is that the code you have provided counts up and you have requested that it count down.
Change secondes++; and minutes++; with:
secondes--;
minutes--;

Lastly you need to change the logic for when the secondes and minutes variables reach zero.
If the secondes variable reaches zero but the minutes variable is greater than zero, then you decrement the minutes (using the line of code provided above) and top-up the secondes with 59.
secondes = 59;

You will need to check the value of the secondes and minutes variables using a couple of if...else statements.
if (secondes == 0 && minutes == 0) {
    // insert your timer finished code here
}
else if ( secondes == 0 && minutes > 0) {
    minutes--;
    secondes = 59;
}
else {
    // Error - your code should not reach here.
    // Display an error message on the LCD
}

This if..else statement will need to go at the top of your loop instead of the end.


Is there some better documentation somewhere for Arduino classes and API's?

What I did/do when loading a new core is generating a doxygen visualisation help class hierachy in HTML. Although most of the core libs have no detailed doxygen documenation the dot/graphviz solves the problem without installation of other IDEs (which also have their specific problems, or need a lot of learning). As an added bonus I can document my source code in a clean and transparent way available in most IDEs and OS.


SRF04 Ultrasonic sensor - inaccurate readings

Just don't use that library, it seems poorly designed.

Here is how the distance for roundtrip is calculated (code excerpts):

long sum = 0;
for (int i=0;i<_average;i++)
{
    digitalWrite(_trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(_trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(_trigPin, LOW);
    _duration = pulseIn(_echoPin, HIGH);
    sum=sum+_duration;
}
return(int(sum/_average));

If we remove the averaging stuff (as _average is 1 by default), this boils down to:

digitalWrite(_trigPin, LOW);
delayMicroseconds(2);
digitalWrite(_trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(_trigPin, LOW);
return int(pulseIn(_echoPin, HIGH));

pulseIn normally returns an unsigned long which is the number of microseconds for a roundtrip of the sound wave emitted by the sensor.

If we consider the speed of sound in the air to be about 340m/s (under average conditions of temperature and altitude), and if we consider an object that is 3m away from your sensor (which is the approximate max range of the SRF04 sensor), then pulseIn() should return:

3 x 2 / 340 x 1000000 = 17646 us

So far we don't see any particular problem, that's fine.

Now, if we take a look at the SRF04 datasheet timing diagram, it is mentioned that if no object is detected, an echo of 36ms will be sent by the sensor; in this situation, pulseIn() will return 36000us.

The problem here is that 36000 does not fit into an int (max value = 32767), the conversion to an int will change it into a negative value! That explains your strange negative outputs.

Now regarding accuracy, the library you are using has another issue; here is how the distance in cm is calculated:

int DistanceSRF04::getDistanceCentimeter()
{
        return (getDistanceTime()/29/2);
}

The problem here is the int calculation, it should rather be performed as float. For a speed of sound of 340 m/s, one should divide the time of the echo in us by 29.4 (ie 1000000 / 340 / 100), not 29, that can make a difference in the final calculated distance!

If you want to go on using this library, then just forget about the getDistanceCentimeter()method and replace it with the following code:

distance = (int) (sensor.getDistanceTime() / 29.4 / 2);

All calculation is then performed as float and converted to int distance only at the end.

Your code should also explicitly detect negative values as meaning "no object detected".


Looking for a sensor that measures heart/pulse rate

The commonly used approach is to use an infrared source and sensor pressed against the skin.  Usually the finger tip is all that is needed. In addition to pulse, many have also incorporated an Oxygen measurement feature.

The 1st sensor you linked to appears to use this approach.  But instead of buying a ready made sensor, many have made a project of building their own...

This project has been done and published many times on the Internet.  There are well documented projects such as this one from Rutgeurs.  As well as this complex one from a journal called EDN.  And this one and this one from various independent hackers.


Sending string over serial to nodejs app. Why does it get chunked?

It seems I needed to add a parser to SerialPort nodejs module, in order to specify how the input should be treated.

I changed my code to this:

var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline

var serialPort = new SerialPort('/dev/ttyACM0', {
  baudrate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
  console.log('data received: ' + data)
})

serialPort.on('open', function () {
  console.log('Communication is on!')
})

Basically, I'm specifying a Readline parser, which matches with the Serial.println function calls on my arduino sketch. Now the console output works as expected:

Communication is on!
data received: Found ILI9341 LCD driver


In this loop

while(client.available()) {
    Serial.write(client.read());
    buffer[ctr] = client.read();

you're using client.read() twice, so the buffer gets only every second character.

A solution could be:

while(client.available()) {
    int c = client.read();
    Serial.write(c);
    buffer[ctr] = c;


Decreasing large DC motor power usage by coasting

I suggest you also consider the load going up in inclines. if you turn off the engine going uphill based on speed, you're most likely to turn it on again soon because of the load. You might be able to get a hint of load from the current drawn by the motor. Combining speed and load might also optimize your bike going downhill.


Multiple 3-wire SPI sensor interfacing with Arduino

First off ditch that library. It's completely pointless and actually makes things harder.

Secondly connect your sensors to the SPI pins, selecting a new CS pin for each sensor.

Arduino SCK (pin 13) to all the SCK pins.
Arduino MISO (pin 12) to all the SO pins.
Individual GPIO pins to individual CS pins (use pin 10 for one of them).

Then just use a simple function to read the data using the SPI library (adapted from the library you link to). For instance with CS on 10 an 9:

#include <SPI.h>

double readCelsius(uint8_t cs) {
    uint16_t v;

    digitalWrite(cs, LOW);
    v = SPI.transfer(0x00);
    v <<= 8;
    v |= SPI.transfer(0x00);
    digitalWrite(cs, HIGH);

    if (v & 0x4) {
        // uh oh, no thermocouple attached!
        return NAN;
    }

    v >>= 3;

    return v*0.25;
}

void setup() {
    SPI.begin();
    pinMode(10, OUTPUT);
    pinMode(9, OUTPUT);
    digitalWrite(10, HIGH);
    digitalWrite(9, HIGH);

    Serial.begin(115200);
}

void loop() {
    Serial.print(readCelsius(10));
    Serial.print(" ");
    Serial.println(readCelsius(9));
    delay(1000);
}


The problem is the following:

The digispark core already implements the TIMER1_OVF_vect ISR (Timer1 Overflow Interrupt). Since you have a 1 for the #define TIMER_TO_USE_FOR_MILLIS, Timer1 will be used for counting the millis() value in the background. For this the Timer 1 Overflow interrupt is needed.

The code, that you copied from that site, does not anticipate, that you might use a core, that already implements the interrupts. It is written for a generic ATtiny85, not specifically for the Digispark version.

What you can do to solve the problem:

You can use Timer0 for your code, keeping the Digispark core untouched. You can change all registers from Timer1 to Timer0 (by replacing the 1 with a 0). Additionally you need to replace TCCR1 with TCCR0B, because for Timer0 that's the register, that set's the prescaler (and turns the timer off if zero is written to it). Also you need to consider, that Timer0 has other prescaler settings. So the line TCCR1 = B00001011; in zeroCrossingInterrupt()  must be changed to TCCR0B = B00000101;. That will set the prescaler to 1024 as mentioned in the comment. The resulting code compiles fine for me with the digispark core (though I have not tested it's functionality).
You can set the Digispark core to use Timer0 for millis(), by changing the definition of TIMER_TO_USE_FOR_MILLIS in the Attiny85 section of the file arduino_folder/packages/digistump/hardware/avr/1.6.7/cores/tiny/core_build_options.h to the value 0 instead of 1. If you do this, the original sketch compiles fine. Though the comment before that build options states, that Timer1 is better for millis() "for various reasons", which is not very specific. You can try, if it works good for you.
You can use another Attiny core. Though you might have to change it too, to accomodate for the unusual clock frequency fo 16.5MHz (most cores I have seen have 16, 8 and 1MHz). That might be as easy as changing the value of the defined clock speed in the cores files, but I'm not sure about that.


At dimming = 128, suddenly voltage goes up to 240 volt and then back to 0 volt

int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

The code comments explicitly tell you that the range is 0-128; while non-trivial to do safely, digging out a scope to understand what exactly happens on overflow could be interesting (for example, it may skip alternate half cycles), but the obvious solution is to never command values outside that range, and clamp any out-of-range values which might be requested over the serial port to the limits.

Given that the timing is done unreliably in software, the precise phase behavior of your zero cross detector may be different than the original author's and the line frequency and pulse width constants may or may not be correct for your location, it's not really surprising that you are seeing 128 fall outside the limit of proper behavior rather than just within it.  Likely you want to be conservative in what you allow.

To avoid inconcistency, even better than clamping the maximum value, you may simply want to treat everything above a chosen delay limit as an absolute "off" by simply finishing the ISR immediately without firing the triac at all.  This may prove a lot simpler than trying to reliably find a delay limit that is "almost entirely" off without sometimes slipping over to firing right at the start of the next half cycle - and who really uses the "barely even on" range anyway?

Technically, depending on what the actual memory access width and alignment rules of the ESP8266 are, the sharing of a potentially non-atomic variable between the main and interrupt contexts could cause a one time glitch when it is changed (though even that is unlikely for your expected range of values, especially if you do the limiting before assignment to the shared variable). However, the atomicity concern can be simply remedied by using a volatile unsigned char (or more portably including stdint.h and using a volatile uint8_t) as the shared variable. The volatile keyword is used to require that the compiler actually calculate a variable that may not appear to be used, and actually store it in memory rather than merely cache it in a register.

It's worth noting that the software timed dimming, while somewhat portable is not particularly reliable, and may at high degrees of delay mean the processor spends almost all of its time in the ISR.  For this reason it is generally better to use a hardware timer for this purpose, however that then becomes more chip-specific.  If you are hoping to have things life WiFi running on your ESP8266 at the same time, you'll almost certainly want to move to a hardware timer to avoid glitching.

Ultimately it seems that the tutorial your are following is a poor one, such that doing a complete from-scratch reimplementation would be wise.  Additionally, mains-powered dimming circuits present many safety and reliability concerns even when driving a lightbulb - and it is by no means clear that your triac and snubber circuit are safe to use with an inductive load.  This is a challenging project, and not necessarily an appropriate one to attempt without deep experience.  You might want to consider using a DC fan PWM-controlled from a well-engineered low-voltage power supply instead.


How can I connect an Arduino / ESP8266 to an Azure MySQL database?

Not sure how you would directly connect with an C++ embedded file. One way you could achieve this is by creating a computer application and connect to the machine via Bluetooth.

{Arduino}
* Intake information
* Process into commands
* Push through software serial ----(Blue Tooth-----> { PC or MAC}
                                                    *Create C# or Swift App
                                                    *Intake information via COM-PORT
                                                    *Prepare SQL command with serial data
                                                    *Push to database server

This may of not of been the method you were looking for, but it's a way I found around the issue when working with Azure Databases and Arduino Micro-Controllers. An alternative is going to Raspberry Pi which has a little more resources to deal with server functions.

Hope this helps.


The CD4510 does not seem at all appropriate for this task. It is a counter chip that counts up or down. You can do that with the Arduino. The output (of the CD4510) would be in "binary" and not suitable for driving a 7-segment display.

You can get 8 digit 7-segment displays on eBay for around $2. Surely that fits within your budget?


You can indeed simultaneously read and write through the serial port. At
the hardware level, the serial port (the UART) is a transmitter and a
receiver, which are almost independent. At the software level, they are
both handled through interrupts that read from / write to a software
buffer.

There is, however, a limitation you should be aware of: the software
buffers are not large, typically 64 bytes on AVR-based boards. If
you try to write too much too often, the output buffer will fill out,
and then all subsequent writes become blocking, and run as slow as the
serial port itself. If you receive lots of data and do not read it soon
enough, the input buffer will overflow, and you loose some data.

From your description of your issue, it would seem you are hitting the
limits of both buffers. You Serial.println() too much, too often. Then
these write operations take too long and, in the meanwhile, you do not
Serial.read(). Since your PC is not waiting for you to
Serial.read(), your input buffer eventually overflows, and you only
get slightly more than a buffer worth of characters.


Speeding up Girino gives strange readouts

From the ATmega328P datasheet, section 29.8, "ADC Characteristics":

  Clock Frequency — Min.: 50kHz, Max: 1000kHz

With a 16MHz system clock this means that a /16 prescaler is the most the ADC is considered reliable under for a reasonable 10 bit result (for a full 10 bit result the maximum frequency is 200kHz, which corresponds to a prescaler of /80).

As the frequency increases the sample-and-hold circuitry of the ADC gets less time to do the "sample" part before conversion begins. As such any correctness goes out the window, certainly at the lower bits. The fact that you got any sort of result that you did at /4 is luck.

TL;DR: The ADC is too slow.


I found this to get me started.

http://apexlogic.net/code-bank/arduino/serial-gps-find-distance-between-two-points/


Can't create an array of type const char*

const char* book[amtBooks] is an array of pointers.
"" is an array of chars (with only a NUL character).

You can initialize an array of chars with an array of chars:

const char foo[] = "hello";

You can also initialize a pointer to char with an array of chars:

const char *bar = "good bye";

this works because of the “decay to pointer” feature of C and C++.

But initializing an array of pointers with an array of chars simply does
not make sense. An array of pointers to char could be initialized as

const char *book[] = {"hello", "good bye"};


Sharing serial output from one to many arduinos (plus a computer) via USB hub

First, read a bit about USB, it is an entire protocol, not just a hardware/pin based interface. It is actually quite involved. Then it will be clearer to you why a USB (from the Nano) solution will be... difficult.

Based on my understanding, I would use your #2 idea and what has been suggested, and do the following...

Setup the Uno as a USB slave, not a master.
Using the PC, connect to the Uno and the Trinkets.
When the PC gets data from the Uno have the PC "repeat" it to the Trinkets.

I think this will be the easiest and quickest solution.


data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

That line places a 0 in the byte following the array.

If you define an array of size [x] you have slices [0] to [x-1] available. If you try accessing [x] you will be altering other items on the stack after the array.

That's called a buffer overrun and is one of the most common causes of programs crashing.

If you want to put a 0 at the end of the array, you should use

data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE] = 0; // adding null terminator

You should also check that the strtok() calls actually return a valid pointer. If the incoming string is not in the right format and strtok() can't split the string up, it will return NULL. If you then try and access that NULL pointer as if it were a valid array you will have a nasty crash.


In the setup there is some settings for timer2, but no change of prescaller, so the timer stays stopped.

Obviously it was started by calling soundBuzzer() somewhere in code. But this function name is now kinda misleading. Just set prescaller in the setup and it should be working.


delay() problem for 74HC595 and 7-segment

With the displays which use shift register to light multiple seven segment digit blocks, the register lights up only one digit at a time. The illusion of multiple digits lit is created by fast switching the digits in round. Small delays in this cause the number to look dim, larger delays create flickering and long delays show only one digit lit. So a sketch handling this type of display must run without delays.
In this type of sketch, everything must be handled without delays, so if some sensor requires a delay, start the reading and a millis timer and after the elapsed time read the result.
There are displays using specialized chips, for example TM1637D, which handle the seven segments even if your sketch stops in delay.

adoption of the BlinkWithoutDelay basic example for your algorithm:
unsigned long previousMillis = 0;
const long interval = 1000;
int i, j, k;

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

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

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    k++;
    if ( k == 10) {
      k = 0;
      j++;
      if (j == 10) {
        j = 0;
        i++;
        if (i == 10) {
          i = 0;
        }
      }
    }
    Serial.print(i);
    Serial.print(j);
    Serial.println(k);
  }
}


Yes you can very easy generate an PWM Output with an Arduino:

void setup()

{

  pinMode(pwmPin, OUTPUT);   // sets the pin as output

}

void loop()

{

  analogWrite(pwmPin, yourWantedValue);  // analogWrite values from 0 to 255

}

  On most Arduino boards (those with the ATmega168 or ATmega328), this
  function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it
  works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8
  only support analogWrite() on pins 9, 10, and 11.

  The Arduino Due supports analogWrite() on pins 2 through 13, plus pins
  DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to
  Analog converters, and act as true analog outputs.

Visit quote origin for more Information.


How to read differential TTL signal from encoder using Arduino?

It looks to me like something similar to RS485 (I have a page about that here).

You could use a chip like the LTC1480 to take the A+ and A- inputs and convert them to TTL levels.

I haven't tried it with your encoder but in principle it should work. (You would need two chips if you want to handle A+/A- and B+/B-. Or three if you want to handle R+/R- as well). Still, it's about a $6 chip.


How many times can I upload a program or sketch to my Arduino Uno Clone Board?

He's talking complete and utter gibberish.  To quote from the ATMega328P datasheet:

  High Endurance Non-volatile Memory Segments

  32KBytes of In-System Self-Programmable Flash program
  Memory
  1KBytes EEPROM
  2KBytes Internal SRAM
  Write/Erase Cycles: 10,000 Flash/100,000 EEPROM
  Data Retention: 20 years at 85°C/100 years at 25°C(1)
  Optional Boot Code Section with Independent Lock Bits

  In-System Programming by On-chip Boot Program
  True Read-While-Write Operation

  Programming Lock for Software Security

So you have at least 10,000 uses out of it before it starts to go flakey.


How do I use PlatformIO to flash ESP-12F (ESP8266MOD)

At the PlatformIO community I asked the same question, and pfeerick  suggested to add a build flag.

  It’s most likely the onboard LED is on GPIO2, not GPIO1 so try adding

  build_flags = -D LED_BUILTIN=2 to your platformio.ini … hopefully that
  kicks in before the pins_arduino.h defintion.

But It didn't did the trick.
And the compiler throws a bunch of warnings.
What I did to make it work is to ignore LED_BUILTIN constant and use 2 instead.

#include <Arduino.h>
void setup() {
 pinMode(2, OUTPUT);
}

void loop()
{
  digitalWrite(2,LOW);
  delay(200);
  digitalWrite(2,HIGH);
  delay(200);
}


The easiest and most time efficent way to connect to the internet regardless of the cost

The Arduino Uno and Arduino Ethernet are very simple to program, to connect it to the Internet.

I never used the Yun Arduino, but it seems a little bit harder.


Microcontroller software shutdown with transistor 2N4401

Your question is rather confusing, but some problems are evident just from looking at the schematic:

The schematic is crap.  I have no idea what you're trying to say with the dotted line between the - terminal of the the battery and the processor GND pin.

The line going thru the middle of the transistor is apparently meant to be the connection to the base, but this is sloppy at best.

It took me a while to realize you have the positive power connection at bottom and the ground at top.  Don't do that.

All these things make your schematic hard to read.  Now that I've had to waste time deciphering the schematic, I'll be more brief once we get to talking about the circuit itself.

You say the transistor is a 2N4401, which is NPN, but you show a PNP.  Huh?  Which is it?

There is no base resistor.  The E-B junction looks like a diode to the driving circuit.  When the digital output tries to go low, it will be held one diode drop below power.  That could damager the digital output or collapse the power supply.

Update

You have edited the schematic to show a NPN, but now you have a chip trying to drive itself thru a emitter follower.  The switch also does nothing at all since both its ends are already shorted together.


Load cell weight distribution on rectangular shape instead of square

Newton's second law says that if a force acts on a mass, that mass will accelerate at a rate proportional to the force and inversely proportional to the mass.
All that means for your scale is that if you are not being accelerated up or down, the net vertical force on your body must be 0. Since your body has weight, and the net vertical force on your body is 0 (you aren't accelerating, are you? :) then the downward force must be balanced by an exactly equal upward force. That upward force is the sum of the upward forces exerted by each load cell. Their contributions may individually change depending on where you stand, but their sum must exactly equal your weight.
Note that we have said nothing about the placement of the cells! If your platform allows it, you could move one of the cells 6 (or 60 or 600) feet away from the the others, for instance. The total upward force must still be the same.
So the bottom line is:
F_lc1 + F_lc2 + F_lc3 + F_lc4 == your weight
no matter where you place the cells.


Last element of a struct disappearing on write/read

Modified my struct by changing the first two elements from float to int.

struct weather {
  int tempData;
  int humData;
  float pressData;
}
weather wData;

Everything transmits fine now. I don't really need the precision of a float for temperature and humidity. However, I would still like to find the problem. Could there be some problem with the size of three floats versus two ints and a float? Serial.print(sizeof(wData)) is 12 when all elements are floats and 8 when using two int and a float. My understanding is the NRF24L01+ has a transmit and receive buffer of 32 bytes.


I don't know enough about how tapes work to comment on the sense of what you're doing, but some problems with the code:

You are reading the input and setting buttonstate once only in setup(). You need to read it repeatedly, by putting it in loop().

You also have three variables called state: one global which is never set, and two with very restricted scope which are set but never used - they go out of scope immediately. Remove the ints where you set state in your loop().

This part is useless because you've already done it just above, but probably not hurting anything:

if (stopState == LOW) {
    state = STOP;
}

That's as far as I got. If that doesn't fix it, consider adding trace: you'd have found these two problems pretty quickly if you'd printed out the variables to check your assumptions.


Arduino Uno + Wifi Shield + PS2 Keyboard + LCD Display

Sorry I do not have enough reputation to place a comment.

@Valentin from the link, you provided, to the wifi shield it states that it uses pins 11 ,12 and 13 on the UNO which will give you a conflict on pins 11 and 12 with the LCD. Not sure why that manifests as an apparent keyboard error though:

From the linked page:

  Arduino communicates with both the Wifi shield's processor and SD card using the SPI bus (through the ICSP header). This is on digital pins 11, 12, and 13 on the Uno and pins 50, >51, and 52 on the Mega. On both boards, pin 10 is used to select the HDG204 and pin 4 for >the SD card. These pins cannot be used for general I/O. On the Mega, the hardware SS pin, >53, is not used to select either the HDG204 or the SD card, but it must be kept as an output or the SPI interface won't work.

Again sorry this is not a full answer but thought it may help.


Using Arduino Wifi Shield to Receive Signal

Look for the Web Server example in the arduino IDE.  That will give you a starting point to allow you to control the arduino via a web page.  This tutorial is also very in depth : https://startingelectronics.org/articles/arduino/switch-and-web-page-button-LED-control/


How to load program into Arduino pro mini using FTDI cable?

For the Arduino Nano:

NO, the Nano already includes the USB-to-TTL conversion circuitry. Just use the USB connector as you would with a Uno.

For the Arduino Pro Mini:

YES, you need an external breakout board to perform USB-to-TTL conversion. This board may use the FT232RL chip, but also any other equivalent one like the CH340G. You only need to have the adequate driver in your computer and you'll be set.

NOTE:

If you have "converter cable" you might not need a breakout board because this kind of cable already includes the FT232R (or equivalent). You don't need to use this cable with the Nano.


1) start simple - adding extra features will not help you, especially if you have a deadline

2) implement and test code for each low level function separately - however, in case you use libraries and or snippets, make sure that if a library/snippet requires exclusive use of a certain feature (ex: a timer), others do not need it.

3) test the overall logic elsewhere, where it easier to debug (ex: on a PC), by replacing the actual function calls to low level actuators/sensors with mockup functions that do I/O through either a file or a console.

Said this, what do you mean that you didn't understand the examples you found? To understand most of them, you need at least to read the API/interface of the libraries they use. And also reading the reference manual of the ATMega328P for the HW blocks referred by each library will help getting an overall feeling of what the library does.

About the basic physical model: once you have 4 DC motors (but 2 plus a caster would be enough), why do you want to add a stepper? Youc could do all of it with just 2 stepper motors , which will give you a simpler way to control precisely the orientation of the robot.

I'd suggest you to get the basic movement sorted out, before worrying about the rest. Just make sure that it doesn't make exclusive use of the microcontroller.


Quadcopters usually use 2-PID loops per axis, a rate loop and an angle loop.

Your quadcopter needs to be very aggressive about its rate of rotation but relatively relaxed about how quickly it returns its angle to the center so it doesn't overshoot. With a single PID it will either be too slow to correct or overshoot and oscillate with no "usable" range of tunings in-between, because in order for its outputs to be strong enough to control the quad it will necessarily be too aggressive to smoothly align with the center position. There is a lot of math that explains why this cannot be achieved with a single loop more rigorously if you care to look into it.

So try setting it up with a PitchAngle PID whose output is the setpoint of a PitchRate PID loop whose output goes to the motors, and similarly with the Roll.

That is only one possible problem though, there is a huge number of things that could be wrong. Are your pitch and roll measurements angles to the horizon or euler angles? how fast is your loop running? Are oscillations induced by the motors causing your accelerometer reading/attitude filter combo to be unusable? Are the PID parameters correct? Is the accelerometer's bias calibrated? Is the gyro drift calibrated? Are all you ESC's calibrated the same way?


Why is Serial.begin(9600) interfering with my multiplexor functioning?

(Digital) Pins 0 and 1 are used by the hardware serial port you initialize with Serial.begin() on a classic Arduino like an Uno.

With this type of board it is generally best not to use those for any other purpose; if you do, you have to accept that you cannot use the hardware serial for input or debug/status output.

Even if you don't want to use serial during the operation of the your creation, having those pins connected to other functions can interefere with uploading sketches via the bootloader, or else the act of uploading a sketch can misoperate the functions connected to those pins.


As you can read in the MPU-6050's datasheet, it uses the I2C address 0b110100X, where X is the state of the pin AD0. If you wire AD0 to ground, the address will be 0b1101000, whereas if you wire it to Vcc it will be 0b1101001. That is equivalent to the addresses 0x68 and 0x69.

That means, that - depending on how you wire AD0 - you can have 2 distinct MPU-6050's on the same I2C bus (you cannot have devices with the same address).

If you really need to connect more than 2 of them, you have to use an I2C multiplexer like PCA9544A, which will divide the bus down to sub-busses.

EDIT: Usually the address pins of I2C devices are set permanently by wiring them either to ground or Vcc. The sense of the address system is, that a slave device will stay at it's address, not changing it. But as Jot reported in the comments and as the Arduino Playground site of the MPU-6050 confirms, you can actually set the address pin of the MPU-6050 during operation.

You need 1 digital output pin on your Uno for each MPU, which then get's tied to the MPU's AD0 pin via a voltage divider. The last part is important: You need a voltage divider, because the MPU is a 3.3V device, while the Uno works with 5V. To avoid frying the address pin, you need to step down the voltage.

Then you would use the address pins to set all MPU's to one address (let's say 0x69). When you need to communicate with one of them, you toggle it's address pin, which will change it's address (in this case to 0x68). Then you can use the normal I2C workflow with this address (0x68). When you are done, you can put this MPU back to the other address by again toggling the address pin. You can repeat this with any of the connected MPU's, which can be many (I think the limit here is the I2C bus itself with it's wires capacity).

This is a workaround and not really, what the I2C bus is meant for. But it seems to be valid solution. Just be sure, that the addresses, that you communicate with, are always unique. Contacting an address, which belongs to more than 1 device, will block your I2C bus.


Judging from your example usage, you want the filenames to be built by
the IPmonitoring constructor. However, since that class cannot know in
advance how much space is needed for the file names, you are left with
two choices:

Let those file names be data members: arrays of char of some fixed
size. This will impose a limit on the maximum file name length.

Allocate the arrays dynamically at construction time.

Here is a tentative implementation of the second approach:
class IPmonitoring
{
private:
    const char *_IP;
    const char *_nick;
    const char *connectionLOG_filename;
    const char *disconnectionLOG_filename;
    flashLOG connectionLOG;
    flashLOG disconnectionLOG;

    // Return a dynamically allocated string with the concatenation
    // of `a' and `b'.
    const char *str_concat(const char *a, const char *b)
    {
        char *s = new char[strlen(a) + strlen(b) + 1];
        strcpy(s, a);
        strcat(s, b);
        return s;
    }

public:
    IPmonitoring(const char *IP, const char *nick)
        : _IP(IP), _nick(nick),
        connectionLOG_filename(str_concat(nick, "_connlog.txt")),
        disconnectionLOG_filename(str_concat(nick, "_disconnlog.txt")),
        connectionLOG(connectionLOG_filename),
        disconnectionLOG(disconnectionLOG_filename)
    {}

    ~IPmonitoring(){
        delete[] connectionLOG_filename;
        delete[] disconnectionLOG_filename;
    }
};

Note the destructor, which is needed to avoid memory leaks, unless all
the instances of the class are statically allocated (which would be good
to avoid memory fragmentation). You may want to implement a copy
constructor and a copy assignment operator, as per the rule of
three.


The most effective way to format numbers on Arduino

Here is my try at it: The usual way to write a number in decimal is to
get the digits from right to left with a loop that looks something like

digit = '0' + val % 10;
val /= 10;

The following function does exactly this, with the addition of adding
commas at the correct positions:

/*
 * Format an unsigned long (32 bits) into a string in the format
 * "23,854,972".
 *
 * The provided buffer must be at least 14 bytes long. The number will
 * be right-adjusted in the buffer. Returns a pointer to the first
 * digit.
 */
char *ultoa(unsigned long val, char *s)
{
    char *p = s + 13;
    *p = '\0';
    do {
        if ((p - s) % 4 == 2)
            *--p = ',';
        *--p = '0' + val % 10;
        val /= 10;
    } while (val);
    return p;
}

Note that the string is right adjusted in the buffer, and the unused
characters are not touched. This means you can get a right adjusted
string by:

pre-filling the string with spaces (for padding)
calling the function above
using the original buffer as the right adjusted string

Otherwise you would use the returned pointer to have a string with no
padding.

Here is a simple test program:

unsigned long vals[] = {0, 1, 2, 9, 10, 999, 1000, 0xffffffff};
const int COUNT = sizeof vals / sizeof vals[0];

void setup()
{
    Serial.begin(9600);
    char buffer[14];
    for (int i = 0; i < COUNT; i++) {
        unsigned long val = vals[i];
        Serial.print(val);
        Serial.write('\t');
        Serial.println(ultoa(val, buffer));
    }
}

void loop() {}


For the most basic circuit you must bias your microphone since it is electret with a 10k pull up resitor. If you do not want to build a complex circuit you could use a breakout board such as this one.  To build your own see here. It is used as a VU meter which is basically the same idea.  Also, make sure you observe polarity(pin with traces touching metal packaging is negative).


Constantly read analog in in SWITCH/CASE setup

The problem is that it will only go through the POT case once, if you want it to repeatedly read the potentiometer, and then change the LED brightness, you would have to put the case in a loop.

So, you might do something like this:

case POT:
int Mode = digitalRead(BUTTONPIN);
while(Mode == LOW) {
    val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        state = OFF;
        break;
        Mode = digitalRead(BUTTONPIN);
    }
}

If you want to use the debounce, do something like this:

static enum { OFF, ON, POT } state;
unsigned long now = millis();
int x = 0;

while (x == 0) {
    switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        if (button_press()) {
        state = ON;
        }
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        if (button_press()) {
        state = POT;
        }
        break;
    case POT:
        val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        if (button_press()) {
        state = OFF;
        }
        break;
    }
}

This should work. What it's doing is basically just going through this while loop over and over and over again, and whenever the button is pressed, THEN it will switch state, but otherwise, it'l just do the same state again and again. This way the potentiometer will work AND the debounce.


Scroll one line of text while another line is static on a SSD1306 OLED

I just found the answer on the following site: https://lastminuteengineers.com/oled-display-arduino-tutorial/

Basically, the method startscroll* on the display takes some arguments.
By passing the proper start page and stope page you can scroll parts of the screen.

Refer to OLED Memory Map for explanation of the pages on the screen. There are eight pages in the display from 0 to 7, so we can scroll a certain part of the screen by passing specific page numbers as parameters.

In this example, we pass both the parameters as 0x00. This will scoll the first page only (first 8 rows) of the display:

// Scroll part of the screen
display.setCursor(0,0);
display.setTextSize(1);
display.println("Scroll");
display.println("some part");
display.println("of the screen.");
display.display();
display.startscrollright(0x00, 0x00);

Source: https://lastminuteengineers.com/oled-display-arduino-tutorial/


Storing data (strings) if ethernet fails to send it

In my opinion SD would be the best way because it is cheap, small, relatively fast and easily portable on a PC, using FAT (but it uses a lot of resources) or even raw; but then you have to use some more trick to get to the raw data from a OS, its not just "plug n read".

The SD library uses FAT under the hood, and it gives you a nice and easy interface. Just remember that SD works at 3.3V, and connecting them directly to arduino will break them fast, even if often not immediately.


Read analog signal over the SPI bus using MCP3201 ADC and Arduino Uno

It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?

Of course it is. VREF is purely a reference voltage for taking measurements. It has no other role.

If you look at the functional block diagram from the datasheet:

You can plainly see that VREF is only connected to the DAC that is used as part of the SAR feedback loop. Everything else is fed from VDD


Why is Arduino I2C so sensitive to RFI/EMI?

Put a ground plate between your data lines and the power+signal lines used to drive the motor. A GPS ground plate is fine, see link below. You can just cut a piece of metal sheet to fit, or even use folded metal foil connected to ground. Motors are just noisy, and I2C is sensitive. Even updating a I2C LCD can cause noise. I like to use shielded wire (like for headphone- or HDMI cable) if my data lines are more than an inch long. You can shield lines with metal foil and heatshrink, but that’s a mess.

Use an opto-isolator to turn on your motors if a ground plate is not enough. If they only drive in one direction, add a catch diode and a 330pF cap to trim the noise. But they are probably most noisy when running. Good luck with that.

https://www.imnasa.com/en/ground-plate-200x64x12mm-for-gps-etc.html


I am the designer of the RGB Shades and co-own macetech LLC. The RFDuino specifications claim only 18mA on transmit and receive, so there should not be a current draw issue from that module.

Known power issues with the RGB Shades include high current draw on startup. They can pulse about 1.3 amps (the blue flash) before your software sets them to a more reasonable level. Most USB power packs made today can handle 1.0 amps, some can supply more, but it's still common to find packs limited to 500mA...that would be one thing to check.

Since you are using your own code, please also note that our default code on the controller-included RGB Shades sets the maximum brightness to about one-quarter the actual maximum brightness of the LEDs. This is done to conserve power as well as reduce brightness to non-blinding levels. If your code is attempting to operate at normal brightness, please be aware the RGB Shades could draw up to 4 amps.

The best way to detect the problem would be to get a multimeter and compare the supply voltage when connected to your computer and when connected to the USB power pack.


Use the long type instead

long watertime = 300000; // how long to water in miliseconds
long waittime = 3600000; // how long to wait between watering