text:
Power Arduino Due and 6 servo motor with Battery
I would like to create a project contains 6 servo motors and Arduino Due board, but I have no idea how to operate should I use only a 9V battery only or in addition to 4 AAA battery?

That highly depends on the servo motors and how long this project should last with the batteries. You need to give us more details. Look at the data sheets for the servos and see, how much current they draw. With this and the capacity of your batteries you can estimate if this can work. For this also refer to this question

Hello,
i want to know what is the best way to power an arduino due and a 6 servo motors and a HC-05 bluetooth module.
Since the arduino due operating voltage is 3.3V an the servo motors operating voltage is 4.8 ~7.2V  and the HC-05 bluetooth module can operate with 3.3v.
What is the best way to power them ?

There is no best way in general. With your setup you may use a 9V battery as input for the Due (over the power jack, which wants voltage between 7V and 12V) and using a voltage regulator to get maybe 6V from your 9V battery voltage for your servos. Make sure, you get a regulator that can give you enough current for the 6 servos (You can find this info in the datasheet of the servo motors).
Of course you can also drive your project with 2 different battery packages, like you have described it in your question. Note, that you have to connect both grounds to make this work.


text:
2 Motor Robot Control with RC Radio
I am making a robot for a local robotics competition.  One main function I need to do is move it forward, backward, right, left.  Just like an RC car.  I have programmed it to do that but it seems like the motors are not going the same speed as each other.  When I move the stick just a little bit only one motor starts moving then when I go a bit further the only starts as well. I use an L293D and an Arduino UNO to control the 2 12v motors. I use a 6 channel receiver and transmitter for radio control.  I think it might be something with the motor, but I might be missing something.  Hopefully, someone can help me out. Thanks!
int motor1_in1 = 3; //H bridge direction pins
int motor1_in2 = 2; //H bridge direction pins
int motor2_in3 = 7; //H bridge direction pins
int motor2_in4 = 6; //H bridge direction pins

//the following are all ~PWM capable ports
int motor1_enable1 = 4; //H bridge motor 1 PWM PIN
int motor2_enable1 = 5; //H bridge motor 2 PWM PIN
int rc_channel2 = 10;
int rc_channel4 = 8;

void setup() {
  pinMode(rc_channel2, INPUT);
  pinMode(rc_channel4, INPUT);
  pinMode(motor1_in1, OUTPUT);
  pinMode(motor1_in2, OUTPUT);
  pinMode(motor1_enable1, OUTPUT);

  pinMode(motor2_in3, OUTPUT);
  pinMode(motor2_in4, OUTPUT);
  pinMode(motor2_enable1, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  motorMoveForward();
  motorMoveSide();
  // delay(100);
}

void motorMoveForward()  {
  int pwm = 0;
  int rc2 = pulseIn(rc_channel2, HIGH, 25000);

  if (rc2 == 0) {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);
  }
  else if (rc2 > 1520) { //Backwards
    pwm = map(rc2, 1520, 1910, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, HIGH);
    digitalWrite(motor2_in3, HIGH);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, pwm);
    analogWrite(motor2_enable1, pwm);

    Serial.print(" DOWN    : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);

  }
  else if (rc2 < 1480) { //Forwards
    pwm = map(rc2, 1480, 1090, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, HIGH);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, HIGH);

    analogWrite(motor1_enable1, pwm);
    analogWrite(motor2_enable1, pwm);

    Serial.print(" UP     : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);
  }
  else {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);

    Serial.print(" CENTER  : ");
    Serial.print(pwm);
    Serial.print("\t");
    Serial.print(rc2);
  }

}

void motorMoveSide()  {
  int pwm1 = 0;
  int rc4 = pulseIn(rc_channel4, HIGH, 25000);

  if (rc4 > 1520) { //RIGHT
    pwm1 = map(rc4, 1520, 1905, 0, 255); //map our speed to 0-255 range
    //digitalWrite(motor1_in1, LOW);
    // digitalWrite(motor1_in2, HIGH);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, HIGH);

    analogWrite(motor1_enable1, pwm1);
    analogWrite(motor2_enable1, pwm1);

    Serial.print(" RIGHT   : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);

  }
  else if (rc4 < 1480) { //LEFT
    pwm1 = map(rc4, 1480, 1090, 0, 255); //map our speed to 0-255 range
    digitalWrite(motor1_in1, HIGH);
    digitalWrite(motor1_in2, LOW);
    //digitalWrite(motor2_in3, HIGH);
    //digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, pwm1);
    analogWrite(motor2_enable1, pwm1);

    Serial.print(" LEFT    : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);
  }
  else {
    digitalWrite(motor1_in1, LOW);
    digitalWrite(motor1_in2, LOW);
    digitalWrite(motor2_in3, LOW);
    digitalWrite(motor2_in4, LOW);

    analogWrite(motor1_enable1, 0);
    analogWrite(motor2_enable1, 0);

    Serial.print(" CENTER  : ");
    Serial.print(pwm1);
    Serial.print("\t");
    Serial.println(rc4);
  }

}

See the many answers which explain how horrible the L293 is.  Fundamentally this doesn't seem to be a job for an Arduino - what you probably want is a pair of small hobby ESCs.

pulseIn() is an exceptionally bad, blocking way to read in RC signals, and performs very poorly, while also slowing your loop speed down a lot. Reading in RC signals properly is a very advanced task. Here's one example I made to show how to do it properly on a single RC channel: https://github.com/ElectricRCAircraftGuy/eRCaGuy_TimerCounter/blob/master/examples/read_PWM_pulses_on_ANY_pin_via_pin_change_interrupt/read_PWM_pulses_on_ANY_pin_via_pin_change_interrupt.ino. Doing it for many channels is far more complicated still, as jitter and interrupt time must be minimized.

From your code I would say, the problem lies within your loop function. The functions motorMoveForward() and motorMoveSide() are both over very quickly. But to actually move your motors need some time, before you change directions. Currently the motors rapidly change between driving forward and sidewards. Since in your motorMoveSide() function you only change direction for one of the motors, this one will rapidly being told to move forward and backwards. That results in the motor to move slowly or to not move at all. You simply cannot move forward and sidewards at the same time.
If you just want to controll the movement of your robot via RC, it may be better to use one channel just for speed value (for example 0 --> stop, 255 --> full power) and one for the direction (for example 0 --> full power left, 127 --> just forward, 255 --> full power right). A normal RC car works the same way. Or you can take one channel for one motor (and mapping speed and direction of the specific motor like you did with both motors). Which way to go depends also on your remote (e.g. what is best for controlling it with the remote).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Write a condition to execute 2 switch-case functions?
I'm new to programming and using Arduino products, and was wondering if someone wouldn't mind assisting me with a project I'm trying to tackle?
If you review my code below, I have 3 conditions within my "idle" case, and the program is constantly looking for any of those 3 conditions. If the first condition is met, then case 1 is called; if the second condition is met, then case 2 is called; if the third condition is met, then case 3 is called. All 3 cases return to the "idle" case once done running.
What I would like to do is find some way to insert the "warning" case if any of the conditions are met, BEFORE going to case 1, case 2 or case 3, without writing the functions of the "warning" case over each time for each of the other 3 cases. Essentially, the flow would be like this:
condition 1 --> warning --> case 1 --> case idle;
condition 2 --> warning --> case 2 --> case idle;
condition 3 --> warning --> case 3 --> case idle:
void loop() {
  static byte theState = idle;
  switch (theState)
  {
    case idle:
      if (voltageA0 > 1.0) {
        theState = case1;
      }

      if (voltageA1 < 2.0) {
        theState = case2;
      }

      if (voltageA2 > 3.5) {
        theState = case3;
      }
      break;
    case warning:
      digitalWrite(7, HIGH);
      delay(5000);
      digitalWrite(7, LOW);
      delay(0);
      break;
    case 1:
      digitalWrite(8, HIGH);
      delay(2000);
      digitalWrite(8, LOW);
      delay(0);
      theState = idle;
      break;
    case 2:
      digitalWrite(9, HIGH);
      delay(2000);
      digitalWrite(9, LOW);
      delay(0);
      theState = idle;
      break;
    case 3:
      digitalWrite(10, HIGH);
      delay(2000);
      digitalWrite(10, LOW);
      delay(0);
      theState = idle;
      break;
  }
}

Also, if there is a more efficient way to do this, code-wise, I'm all ears!

Simplifying the code before posting it is generally a good thing. But if you change it so much that it becomes mostly unrelated to the original one, then a proper answer to the question may not be applicable to your real problem. Judging from your comments to Look Alterno's answer, this is exactly what happened. The blocking code you posted is a very different beast from the non blocking one you are using. Please, edit the question to make it relevant to your actual problem. This would be more useful than trying to explain in comments the extent to which the codes differ.

There is something incoherent in your code. It is structured as a finite
state machine, and yet you are using delay() within it. In this kind of
scenario, the whole purpose of a state machine is to avoid using
delay(), so that your program never blocks. If your program happens to
not have anything better to do than delaying, then you can forgo the
state machine and write much simpler code. For example:
void warn_and_flash(byte pin)
{
    // Flash the "warning" LED.
    digitalWrite(7, HIGH);
    delay(5000);
    digitalWrite(7, LOW);

    // Flash the requested LED.
    digitalWrite(pin, HIGH);
    delay(2000);
    digitalWrite(pin, LOW);
}

void loop()
{
    if (voltageA0 > 1.0) warn_and_flash(8);
    if (voltageA1 < 2.0) warn_and_flash(9);
    if (voltageA2 > 3.5) warn_and_flash(10);
}

I agree. Imagine you are writing code for a motor car, and the driver puts on the left indicator, which is supposed to flash once every second. Do you really want to the car to ignore the other inputs (brakes, accelerator, air conditioning) for an entire second while you delay for one second? I think not.

case idle:
  if (voltageA0 > 1.0 || voltageA1 < 2.0 || voltageA2 > 3.5) {
     digitalWrite(7, HIGH);
     delay(5000);
     digitalWrite(7, LOW);
     delay(0);

     if (voltageA0 > 1.0) {
        theState = case1;
        }

    if (voltageA1 < 2.0) {
       theState = case2;
       }

    if (voltageA2 > 3.5) {
       theState = case3;
       }
   }

EDIT:
To clarify original answer, I inlined the "warning" code and deleted the "case warning", as obviously this state is not longer needed.

Thanks so much for your assistance guys! I suppose I should have explained why I'm using a state machine for the code. The code I gave the example of omits the millis() functions that I actually have in my real code. I re-wrote the example without the millis() functions to simply what I'm trying to do, but cases "warning", "1", "2", and "3" all use millis() functions to trigger LEDs and relays. Sorry for not explaining that.
Edgar, thanks for pointing out the "delay(0);" redundancy I had... I was thinking that may have been redundant, but wasn't sure. Based on the fact that I need to...

...call a different set of functions after the "warning" function, specific to the condition that was met, I don't believe the example you suggested would work. I may be wrong though so please let me know if I missed something :)
Look Alterno, thank you for your help as well. Something else I didn't explain is that the "warning" state/function also remedies the conditions by triggering relays to cut voltage to some devices. The successive cases (1, 2, 3) are just used as an indicator to tell me which condition was just met, after the warning state remedies the problem.

So think of it this way...
condition 1 will trigger the warning case, then go to case 1, where an LED will flash 5 times to indicate condition 1 was just met
condition 2 will trigger the warning case, then go to case 2, where an LED will flash 10 times to indicate condition 2 was just met
condition 3 will trigger the warning case, then go to case 3, where an LED will flash 10 times to indicate condition 3 was just met
Again, my fault for not elaborating all of this initially. Does this make more sense?? Thanks again, very much, for the help!

@Andrew. That's what the code does: if any condition is met, then warning is executed. After that, the code tests for the specific condition (case 1, 2 or 3) and executed the pertinent action(s).

thanks! But yeah the warning state will remedy any of the 3 conditions, so checking for the condition AFTER the warning state won't do any good unfortunately. The best way to think of it is let's say voltage on pin A0 increases as a pot of water gets hotter. Once the pot of water reaches a certain temperature (voltage), the "warning" function illuminates an LED for, let's say 10 minutes, while also cutting the heat source to the pot of water. Once that 10 mins is up, the condition-related case (1, 2, or 3) will flash an LED a certain number of times to indicate which cond was met

If the water temperature drops below a certain temperature/voltage, then the warning case is triggered, and then case 2 is triggered to flash an LED a different number of times to indicate that condition 2 was triggered. These are not the most sensible examples, but it is easier to explain it that way than what and how I'm truly monitor the inputs on the Analog pins. Hope that makes more sense and thanks again!! :)

@Andrew. See the edited code for better explanation.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Notifications in constant loop (Blynk) trying to trigger along with serial function
This is an extension from a previous thread that was getting lengthy and off the original topic. I have the following code which monitors the state of a float switch (high or low). I upload the sketch, turn on the serial monitor and manually move the float switch up and down. The serial monitor output represents what I'm doing with the switch. The issue is that I get a constant loop of blynk notifications, every 15 seconds or so. Furthermore, if i move the switch to it's low position, the first blynk notification i get is correct reading "low", the following notifications are "high" thereafter. When the switch is moved to the high position, blynk just loops stating it's "high". I know it's weird and took quite a while to even establish what is going on here. but the biggest issue is the loop of notifications every 15 seconds.
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
BlynkTimer timer;

char auth[] = "710a4af9b1d82412fa477705bf642c634";
char ssid[] = "ssid";
char pass[] = "pwd";
int flag=0;
int floatSavedState = -1;      // initial float low state indicates not yet known

void notifyOnButtonPress()
{
  // pin D1 will be 1 if float has dropped due to low water level
  // pin D1 will be 0 if water level is high enough
  int floatLevelLow = digitalRead(D1);  // read the float low indicator pin

  if (floatLevelLow && floatLevelLow != floatSavedState) {
       // send notification if this is first time or if the float level has
       // changed since the last notification.
       Serial.println("Resevoir Water is Low!");
       Blynk.notify("Alert : Water Level low.");
       floatSavedState = floatLevelLow;
  } else if (floatLevelLow != floatSavedState)
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;

}
void setup()
{
  // Debug console
  Serial.begin(9600);
Blynk.begin(auth, ssid, pass);
  // Setup notification button on pin D1
  pinMode(D1,INPUT_PULLUP);
 timer.setInterval(16000L,notifyOnButtonPress);

}
void loop()
{
  Blynk.run();
  timer.run(); // Initiates BlynkTimer
}

Your code:
timer.setInterval(16000L,notifyOnButtonPress);

Is calling this function every 16s.
This code:
if (floatLevelLow && floatLevelLow != floatSavedState) {

needs some parentheses to force your desired order-of-operations. As it stands now, you are asking the result of floatLevelLow && floatLevelLow and comparing if that is not equal to floatSavedState. That's likely not what you want.
Did you mean:
if (floatLevelLow && (floatLevelLow != floatSavedState)) {

EDIT:
Also, your if/else is missing brackets around the 2nd clause and should be:
} else if (floatLevelLow != floatSavedState) {
     // send notification if this is first time or if the float level has
     // changed since the last notification.
     Serial.println("Resevoir Water is High!");
     Blynk.notify("Alert : Water level high");
     floatSavedState = floatLevelLow;
}

Thank you for your help with this! I added the parentheses and it is still acting in the same manner. If I comment out the timer function and the call for it, the sketch does not work at all once compiled.

Your code doesn't have brackets on the 2nd part of the if statement, so your code is calling Serial.println("Resevoir Water is High!"); if the if` is true, but it's always calling the remaining lines. I will update my answer to address this also.

You nailed it!!!! thank you so much, I've spent far too many hours on this!!!!


text:
I keep getting an error message and I don't know how to fix it
I am using an Arduino Genuino, this is what comes up
Multiple libraries were found for "LiquidCrystal.h"
 Used: /home/user/Arduino/libraries/LiquidCrystal
 Not used: /opt/ArduinoIDE/libraries/LiquidCrystal
In file included from /home/user/Arduino/libraries/dht/DHT_U.cpp:22:0:
/home/user/Arduino/libraries/dht/DHT_U.h:25:29: fatal error: Adafruit_Sensor.h: No such file or directory
 #include <Adafruit_Sensor.h>

                             ^
compilation terminated.
exit status 1

what do you understand about what the message is telling you?

The first notice about multiple libraries is not stopping you. The DHU library relies on the Adafruit Unified Sensor Library
You should have the following libraries (installed and) included:
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>


text:
What's a good alternative to an Arduino Nano that can be used with Neopixels?
I'm doing an arduino project in school which requires neopixels, but the Arduino's too big. Is there an arduino I can use that's compatible with neopixels? Thanks!

How big it too big? Have you looked at Arduino Micro or Pro Mini. Even the DigiSpark runs NeoPixels

The Teensy (3.2 and better) OctoWS2811 LED Library is really interesting too.

ESP8266 mini is the best and cheaper alternative 2$5 on Ali express. Then 100% compatible with arduino toolchain/IDE + very impressive community/github library!

There are Arduino ProMinis (they have the same specs as the nano) also there's an arduino digispark tiny 85 (they have lower specs than the nano) and at the end there are just microcontrollers that can be soldered on a PCB that is enough small for you (they have a big range of specs)
Here is a comparison to the nano

It's not really an Arduino, however there is an STM32 which you can program almost identical to an Arduino (using the Arduino IDE). It's the STM32F103C8T6.


text:
Using SD library in a ESP-IDF project on ESP32
I just started to move from the Arduino firmware to the esp-idf firmware.
I read that link. I learn that I have to include libraries creating a component files, with a component.mk file, *.c, *.cpp files and an include/ folder for *.h files.
That was ok for most of libraries I had to include, except for the SD card library, more precisely the Sd2PinMap.h header.
It seems that ESP32 is not recognized:
$(IDF-PATH)/Project/components/SD/include/Sd2PinMap.h:510:2: error:
#error Architecture or board not supported.

but with the Arduino firmware, there were no problems.
I checked make menuconfig options, but I didn't find a way to make it work for an ESP32 board... Any ideas ?

So, this question is about non-Arduino hardware running non-Arduino firmware?

It's about moving from Arduino, to another firmware. I was thinking that arduino.stackexchange was more appropriate for this than stackoverflow, which is too broad. Where am I supposed to ask this ?

Don't get me wrong, I wasn't saying you can't ask, I was just clarifying what your issue was

espressif esp32 forum https://www.esp32.com/

Okay, the solution was simple, I just had to pull the update for the SD Card library, mine was outdated. Thank you all.


text:
Commucinate two arduino with each other
I have 2 arduino Unos where each one works properly on its own.
I try to make them communicate with each other using serial communication (TX-RX ports).
When I try to upload my code to them I get this error :
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
An error occurred while uploading the sketch

what should i do to fix it ? (MY os is windows 10) thanks

Please show us how you have connected the 2 Arduinos together and the sketches you are trying to upload.

have you tried to load the sketch while the arduino has nothing connected to any of the pins?

Pins 0 and 1 on the Arduino Uno are used for serial communication with the computer over USB, including uploading sketches. If you connect anything to those pins you can interfere with the upload process.
To communicate between the two boards using serial communication without using pins 0 and 1 you can do software serial on other pins:
https://www.arduino.cc/en/Reference/SoftwareSerial


text:
Arduino: Reading DS18B20 interferes with servo
I have an Arduino with a servo, INA219 (current and voltage sensor) and 2 DS18B20 connected to it.
DS18B20 are connected in full-power mode with 5k resistor connected between DATA line and +5V.
I use DallasTemperature library: https://github.com/milesburton/Arduino-Temperature-Control-Library
I get the temperature readings, but the problem is that my servo is jittering slightly almost every time temperature reading is done.
If I disconnect DATA line from pin 2 (where it's normally connected) then servo is not moving anymore and everything is fine.
Any ideas what might be causing it? I would expect servo interfering with OneWire readings, not the other way around :)
Here is the full code:
https://pastebin.com/xcES4PVT
Here is the minimal example with which I can reproduce the problem:
    #include <DallasTemperature.h>
#include <Servo.h>

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

Servo myservo;

long previousMillis = 0;

long tempRequestedMillis = 0;

bool tempRequested = false;

void setup(void)
{
  // start serial port
  Serial.begin(115200);
  Serial.println("Dallas Temperature IC Control Library Demo");

  myservo.attach(9);

  // Start up the library
  sensors.begin();
  sensors.setWaitForConversion(false);
}

void loop(void)
{

  unsigned long currentMillis = millis();
  if (!tempRequested && currentMillis - previousMillis > 2000) {
    previousMillis = currentMillis;

    sensors.requestTemperatures(); // Send the command to get temperatures

    tempRequestedMillis = currentMillis;
    tempRequested = true;
  } else if (tempRequested && currentMillis - tempRequestedMillis > 2000) {
    Serial.println(sensors.getTempCByIndex(0));
    tempRequested = false;
  }
}

maybe something is taking up too much time in the loop ... start by commenting out all the serial.print statements

I have the same problem that Leonti. BUt in my case, i have a duemilanove and the lcd shield, that which occupies pins 9 and 10 that I read are the necessary ones in the duemilanove to work with this library. Is there any possibility of using other pins? Is there another library that uses different pins? I have free: A1,A2,A3,11,12 and 13...

Arduino's Servo library on AVR uses interrupts; if interrupts are disabled for any amount of time, the servos will twitch.
1-Wire protocol (used by DS18B20) needs to disable interrupts for the protocol to work. Therefore, servos glitch.
There is a great explanation of the problem here: https://learn.adafruit.com/neopixels-and-servos/overview , just mentally replace "Neopixel library" with "OneWire library". Their TiCo_Servo library sounds just like what you want.

That was it!
After using TiCoServo library there are no issues!
Thanks a lot!

The OneWire library was poorly implemented IMO. It globally disables all interrupts when it only really needs to disable interrupts on the data line. If other interrupts are well behaved and return quickly, it won’t disrupt the One wire timing. I don’t know how to turn my avr code into an Arduino library, but there’s an alternative implementation in my digital thermometer project. https://github.com/rubberduck203/digital-thermometer

Reading a DS18B20 the naive way takes up to 1500ms because you have to trigger a temperature conversion, then wait for it to complete.
If you have them full-powered, you better trigger the conversion, continue with your program and read the result 2 seconds later, when it's done. You can also trigger the conversion on all connected DS18B20 simultaneously by using the Skip ROM command before sending the Convert T command.
Please see the documentation of Maxim/Dallas' library how to do that.

I tried to use setWaitForConversion which shouldn't wait for conversion and then read the results 2 seconds later - still the same problem.
I've attached the minimal code which has the problem, would you mind taking a look at it?

Looks okay, are you sure you aren't accidentally running the old code?


text:
SSD1306 / U8glib display fonts and commands
I cannot seem to find any reference for the SSD 1306 or U8glib display font library or any command reference, like all the options for display() etc. For my fonts I been going into the utility folder and scrolling through notepad for the U8glib library but its very croweded with numbers and code. is there any reference for both libraries online that is user friendly?

First, u8glib is superceded by u8g2
Second, the u8glib wiki has a command reference and font reference.
As does the u8g2 wiki.
Neither reference lists a display() command.

OK GREAT iLL CHECK IT OUT

lots of good info on there, thanks. So I added some font and sometimes I get many symbols (I have a scroll set up) How do you grab just one of those symbols, for example, an arrow?

If you have a different question, post it as a new question.

there is not much variety of fonts available

What are you actually looking to do? There are many fonts and even non-English character set fonts.

display is in the SSD1306 library, is there a wiki for that?

Im just toggling through some functions and have a display to show what mode im in but the default font kind of sucks. Looking for something more creative.

https://github.com/olikraus/u8g2/wiki/fntlistall hundreds

u8g2 handles SSD1306 communication, so you should not need a separate library...

ok Ill have to load the U8g2 into my library

what about icons, like battery indicators, meters, etc. is there librarys with ready made images, or bitmap images?

I wonder if you are even reading or looking at the font lists available on the links. https://github.com/olikraus/u8g2/wiki/fntgrpsiji

yeah I read through all of them, look about the same, adobe old standard etc

trying this one now u8g_font_helvB14, seems to be about the best one

so in that github library you have provided with the siji text, how do I grab one of those icons? I dont need them all

You set the font using something like u8g2.setFont(u8g2_font_siji_t);. Looking at the font diagram, some battery icons start at character position 0xe242 through 0xe24b. You may need to enable UTF8 support with u8g2.enableUTF8Print();. Then, you print a string with the 2-byte 'character', like u8g2.print("\0xe2\0x42"); Note, I haven't tested this myself, but I read the documentation.

Ok I see, I will try it out


text:
using special symbols from the U8glib library
I enter font symbols into the u8g.setFont() and I get a string of sympols. How do I grab just one of those symbols, for example an arrow?

setFont just tell how display the next drawStr (or similar text output function).
To draw an arbitrary UTF8 char, just use
drawUTF8
C++/Arduino Prototype:
u8g2_uint_t U8g2::drawUTF8(u8g2_uint_t x, u8g2_uint_t y, const char *s)

C Prototype:
u8g2_uint_t u8g2_DrawUTF8(u8g2_t *u8g2, u8g2_uint_t x, u8g2_uint_t y, const char *s);

Description:
Draw a string which is encoded as UTF-8. There are two preconditions for the use of this function:

The C/C++/Arduino compiler must support UTF-8 encoding (this is
default for the gnu compiler, which is also used for most Arduino
boards), and
The code editor/IDE must support and store the C/C++/Arduino code as UTF-8 (true for the Arduino IDE).

If these conditions are met, you can use the character with code value greater than 127 directly in the string (of course the character must exist in the font file, see also setFont).
Advantage: No escape codes are required and the source code is more readable. The glyph can be copied and paste into the editor from a "char set" tool.
Disadvantage: The code is less portable and the strlen function will not return the number of visible characters. Use getUTF8Len instead of strlen.
Arguments:
        u8g2: A pointer to the u8g2 structure.
        x, y: Position of the first character on the display.
        s: UTF-8 encoded text.
Returns: Width of the string.
Note 1: This drawing function depends on the current font mode and drawing color.
Note 2: Use the print function to print the value of a numeric variable.
See also: setFont drawStr print
Example:
u8g2.setFont(u8g2_font_unifont_t_symbols);
u8g2.drawUTF8(5, 20, "Snowman: ☃");

wow very cool will try it out

where do you get the icon from?

@Jim. The u8g2 manual is here: https://github.com/olikraus/u8g2/wiki. The font sets are available here https://github.com/olikraus/u8g2/wiki/fntlistall


text:
Reading setting from microSD
I modified the SD sketch for ESP8266 to read WIFI setting from a file named CONFIG.TXT. The text file's content format is SETTING=VALUE. Ex.
SSID=AP001
KEY=AP001

I manage to separate the SETTING and VALUE
My code:
#include <SPI.h>
#include <SD.h>

File myFile;

void readWifiConfig() {
  Serial.println("Initializing SD card...");
  char temp;
  bool isSetting = true;
  if (!SD.begin(4)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");
  myFile = SD.open("CONFIG.TXT");
  if (myFile) {
    Serial.println("CONFIG.TXT");
    while (myFile.available()) {
      temp = myFile.read();
      if (isSetting == true) {
        if (temp == '=') {
          Serial.print("="); //Writes '=' to console
          isSetting  = false;
        }
        else {
          Serial.print(temp); //Writes SETTING part to console
        }
      }
      else {
        if (temp == '\n' || temp == '\r') {
          isSetting = true;
          }
        else {
          Serial.print(temp); //Writes VALUE part to console
          }
        }
    }
    myFile.close();
  } else {
    Serial.println("Can't open CONFIG.TXT");
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);
  readWifiConfig();
}

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

}

Output:
Initializing SD card...
Initialization done.
CONFIG.TXT
SSID=AP001
KEY=AP001

I want to write the values to their corresponding variables and I don't know how.
char* ssid;
char* key;

I don't see a question

You can't just write to a pointer, you need to allocate a buffer and copy the data there.

New and improved code.
File format:
$SETTINGNAME=SETTINGVALUE;

New code:
#include <SPI.h>
#include <SD.h>

File configFile;
uint8_t filePosition;
uint8_t workingIndex = 0;
uint8_t settingNameValuePositions[16][3];
uint8_t temporaryBufferPosition = 0;
char temporaryBuffer[32];

void setPosition(uint8_t mrk) {
  settingNameValuePositions[workingIndex][mrk] = filePosition;
}

uint8_t getPosition(uint8_t idx, uint8_t mrk) {
  return settingNameValuePositions[idx][mrk];
}

void addToBuffer(char inp) {
  temporaryBuffer[temporaryBufferPosition] = inp;
  temporaryBufferPosition++;
}

void resetBuffer() {
  temporaryBufferPosition = 0;
  memset(temporaryBuffer, 0, sizeof(temporaryBuffer));
}

char* requestSetting(char *settingName) {
  for (int i = 0; i < workingIndex; i++) {
    uint8_t nS = getPosition(i,0); //$
    uint8_t eQ = getPosition(i,1); //=
    uint8_t vE = getPosition(i,2); //;
    bool isFound = false;
    resetBuffer();
    for (int g = nS; g < eQ - 1; g++) {
      configFile.seek(g);
      addToBuffer(configFile.read());
    }
    if (strcmp(temporaryBuffer,settingName) == 0) {
      isFound = true;
      resetBuffer();
    }
    for (int g = eQ; g < vE - 1; g++) {
      configFile.seek(g);
      addToBuffer(configFile.read());
    }
    if (isFound) {
      isFound = false;
      return temporaryBuffer;
    }
  }
  return "0";
}

bool readConfigFile(char* fileName) {
  //Serial.println("INITIALIZING SD CARD");
  if (!SD.begin()) {
    //Serial.println("INITIALIZING SD CARD FAILED");
    return false;
  }
  else {
    //Serial.println("INITIALIZING SD CARD COMPLETED");
    //Serial.println("OPENING FILE: " + String(fileName));
    configFile = SD.open(fileName);
    if (!configFile) {
      //Serial.println("ERROR OPENING FILE: " + String(fileName));
      return false;
    }
    else {
      //Serial.println("FILE " + fileName + " OPENED");
      //Serial.println("SEARCHING FOR MARKER POSITIONS");
      while (configFile.available()) {
        char fileChar = configFile.read();
        filePosition = configFile.position();
        switch (fileChar) {
          case '$':
            setPosition(0);
            break;
          case '=':
            setPosition(1);
            break;
          case ';':
            setPosition(2);
            workingIndex++;
        }
      }
    }
    return true;
  }
}

void setup() {
  Serial.begin(115200);
  readConfigFile("CONFIG.TXT"); //FILE NAME
  Serial.println(requestSetting("SETTINGNAME"));
}
void loop() {
}

Somehow I managed to do it but my code is un-optimized. Please let me now if I've done something that isn't good.
I changed the content format to this so it's much easier for me. (CONFIG.TXT)
SSID%&WIFIAP001&%KEY%&PASS1234&

New Code.
#include <SPI.h>
#include <SD.h>

File myFile;
char wifiSsid[63];
char wifiKey[63];
char temp;
char settingSsid[5] = "SSID";
char settingKey[4] = "KEY";
char settingTemp[10];
char valueTemp[63];
int settingTempLastPos = 0;
int valueTempLastPos = 0;
int percentCount = 0;
int andCount = 0;
bool isSetting = true;
bool ssidValueFound = false;
bool keyValueFound = false;

void readWifiConfig() {
  Serial.println("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("Initialization failed!");
    return;
  }
  Serial.println("Initialization done.");
  myFile = SD.open("CONFIG.TXT");
  if (myFile) {
    Serial.println("CONFIG.TXT");
    while (myFile.available()) {
      temp = myFile.read();
      if (temp == '%') {
        percentCount++;
        isSetting = true;
        if (percentCount == 2) {
          //Serial.println(settingTemp);
          if (strcmp(settingSsid,settingTemp) == 0) {
            Serial.println("SSID SETTING FOUND");
            //IF FOUND RAISE FLAG FOR ADDING VALUE TO SSID CHAR ARRAY
            ssidValueFound = true;
            }
          else if (strcmp(settingKey,settingTemp) == 0) {
            Serial.println("KEY SETTING FOUND");
            //IF FOUND RAISE FLAG FOR ADDING VALUE TO SSID CHAR ARRAY
            keyValueFound = true;
            }
          memset(&settingTemp[0], 0, sizeof(settingTemp));
          settingTempLastPos = 0;
          percentCount = 0;
        }
      }
      else if (temp == '&') {
        andCount++;
        isSetting = false;
        if (andCount == 2) {
          //Serial.println(valueTemp);
          if (ssidValueFound) {
            //Serial.println(valueTemp);
            memcpy(wifiSsid,valueTemp,63);
            //Serial.println(wifiSsid);
            ssidValueFound = false;
            }
          else if (keyValueFound) {
            //Serial.println(valueTemp);
            memcpy(wifiKey,valueTemp,63);
            //Serial.println(wifiKey);
            keyValueFound = false;
            }
          memset(&valueTemp[0], 0, sizeof(valueTemp));
          valueTempLastPos = 0;
          andCount = 0;
        }
      }
      else {
        if (isSetting == true) { //setting
          settingTemp[settingTempLastPos] = temp;
          settingTempLastPos++;
        }
        else if (isSetting == false) { //value
          valueTemp[valueTempLastPos] = temp;
          valueTempLastPos++;
        }
      }
    }
    //Serial.println(settingTemp);
    myFile.close();
  } else {
    Serial.println("Can't open CONFIG.TXT");
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  delay(10);
  readWifiConfig();
  Serial.println(wifiSsid);
  Serial.println(wifiKey);
}

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

}

Output:
Initializing SD card...
Initialization done.
CONFIG.TXT
SSID SETTING FOUND
KEY SETTING FOUND
WIFIAP001
PASS1234

uint8_t settingNameValuePositions[16][3];

If you have more than 16 variables it's going to crash your webserver.
If your config file has more than 256 characters, then you should use short instead of uint8_t.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What is the most Inputs on An analog Pin with a specified Accuracy on the Resistors Used?
I am asking about the technique were switches and resistors in series are used on the analog pin, so it creates a voltage divider when one of the switches is pressed, it a well known technique it is described here with 5 buttons on one analog pin
http://www.instructables.com/id/How-to-access-5-buttons-through-1-Arduino-input/
Obviously we assume the circuit is set up correctly e.g. the voltage reference is stable-but such things aren't the main point of this question.
My question is about an obvious generalisation of that circuit for more inputs - and where the resistors are all replaced by, a single type of resistor, a fixed resistance value (e.g. 4k ohm) with a known error on the resistance (e.g. 5%). We use the 4k resistors to make up larger values 4k,8k,12k,16k,20k Ohms and make the 100k Ohm resistor out of twenty five 4k ohm resistors.
My question using only 4k ohm resistors (connected in series in the voltage divider) within a 5% error of their value -what is the most switches  we can theoretically connect for reliable working on one analog pin?-I'll have a guess at 20 switches.
The second question is given X ohm resistors (connected in series in the voltage divider) within a E% error of their value -what is the most switches, M,  we can theoretically connect for reliable working on one analog pin? So there will be a formula for this-so what is it?

Looks like a school assignment ...

As some point even with perfect resistors you will run into noise, impact of dirty contacts, etc...  It's not clear that what precision resistors will gain you over loose tolerance ones would leave enough margin for these concerns, though the situation might be better than pushing the limits of these concerns on top of only approximate resistances.

@LookAlterno Its not a school assignment

@LookAlterno I just wan't to know a formula,or a proof, for the most number of
inputs I can use reliably,as that means I can replicate the circuit reliably,on the arduino with certain resistors
as that would be the cheapest way for me to do the
input of my circuit.

My question using only 4k ohm resistors (connected in series in the
  voltage divider)

The circuit you are describing (a collection of identical resistors
connected in series) is quite different from the one discussed in the
link you provide. I assume you have in mind something analogous to a
digital pot, i.e. a chain of N resistors between GND and Vcc, with N
switches connecting the Arduino analog input to N taps along the chain:
N−1 taps in between consecutive resistors and one extra tap at GND¹.

simulate this circuit – Schematic created using CircuitLab
The push buttons could actually be the multiple contacts of a rotary
switch. If using real push buttons, it would be tricky to know whether a
button is being pushed or if you are just reading noise, though it can
be known by toggling the pin between output and input and using its
stray capacitance.
In this case, the worst case error happens when all the resistors on one
side of the tap are 5% too high, while all those at the other side are
5% too low. It can be easily shown that the minimum possible voltage at
tap k is
V−(k) = k(1−e)/(k(1−e) + (N−k)(1+e))×Vcc
where e = 0.05 is the 5% tolerance of the resistors. The
maximum possible voltage, V+(k), is given by the same formula
after replacing e by −e.
The graph below shows the expected voltage at each tap for a chain of
20 resistors, with the error bars showing the possible voltage
ranges. The blue curves are the analytical expressions of
V−(k) and V+(k).

As can be seen on the graph, the largest error bars are the ones closer
to the central tap. Thus, the buttons can be discriminated accurately if
the two taps closest to the center have non overlapping error bars. This
criterion could be translated into an exact formula, but the formula
would be quite complex and depend on the parity of N. I propose to do
instead some approximations, starting with a first order Taylor
expansion on the error. This expansion gives the length of the error
bars as
V+(k) − V−(k) ≈ 4/N2 k (N−k) e × Vcc
This error is maximal when k = N/2 (we will forget the parity issue):
V+(N/2) − V−(N/2k) ≈ e × Vcc
Then we say that the taps can be discriminated if this error is smaller
than the expected voltage difference between consecutive taps, namely
Vcc/N. Then the criterion is now simply
N ≤ 1/e
which is exactly what your intuition told you.

¹ The extra tap could be at Vcc rather than GND. It would be unwise,
however, to tap both GND and Vcc, as a user pressing both buttons
simultaneously would then short the power supply.

Edit to answer the questions in comments.
Yes, you could use the expressions of V+ and V− to
set the thresholds for discriminating the buttons. For example, you
could set the threshold between k and k+1 halfway between
V+(k) and V−(k+1), i.e.
threshold(k, k+1) = (V+(k) + V−(k+1)) / 2
However, if you try to compute that, you will see that it is extremely
close the average between the expected voltages. Then, you could use
that average as your threshold, which is given by a very simple formula:
threshold(k, k+1) = (k+½)/N×Vcc
Then, the pin number is just the integer closest to Vin/Vcc×N.
Assuming N = 20, this can be written as:
const float VCC = 5.0
float voltage = analogRead(PIN) * VCC / 1024;
int button_number = round(voltage / VCC * 20);

This can be optimized to use only integer arithmetics:
int button_number = (analogRead(PIN) * 5 + 128) >> 8;

Note that 20 buttons is kind of borderline. Your system could fail
if the errors due to resistor inaccuracies and those intrinsic to the
ADC (offset, gain error...) add up the wrong way. If you are building
only one device, then the safest fix would be to take note of the value
analogRead() returns for each button, and set the thresholds halfway
between consecutive values.
You could also measure the resistances of all your resistors, and
arrange them in a way that minimizes the errors. For example, if you
number the resistors from 0 to 19 in order of increasing resistance, I
would build the chain by arranging them in the following order:
0 19 2 17 4 15 6 13 8 11 9 10 7 12 5 14 3 16 1 18
Then you could most likely use the simple formula above to get the
button number at a minimal computing cost.

Yes-you are correct -that is the circuit I had in mind.

Im asking this question because I have a lot of cheap
resistors with the same value and wanted to know what
the most inputs I can get from 1 pin.

So If I chose N=20 resistors, then I could directly use
the analytical expressions of V−(k) and V+(k) to set the
bounds voltage tap k will produce in my arduino sketch?-
-is that correct?

And we dont use tap 20 in practice because V−(20)=V−(20)
i.e. there are no lower and upper bounds

This is the sort of answer I had in mind when I wrote this Meta post.

"Your system could fail if the errors due to resistor inaccuracies and those intrinsic to the ADC (offset, gain error...) add up the wrong way. If you are building only one device, then the safest fix would be to take note of the value"

So if you wanted the safest provable way without measuring any voltages (e.g. for building lots of devices quickly) then you can use tap all the odd taps
as input buttons 1,3,5,...,19 and the theoretical thresholds for would be
V+(k-1)< V(k) < V-(k+1) , for the voltage V(k) from tap (odd numbered) k.

This would give you 9 buttons you can use without the need to know
the actual voltages-measured in some way -it only depends on the
known errors of the known components involved.

So you get theoretically provable lower and upper voltage thresholds, for
each of the  at the cost of using 11 less buttons-you could think of it
as- to make error bounds theoretically computable-without measurement
of some sort-costs 11 resistors.

Is that correct?

The same the same technique is used routinely for 4x4 keypads. You don't really need very precise resistor as long as the final divider produce final voltage that are differente enough.
For each button/key you need to reserve some voltage range for it.
You can expected some random fluctuation every time you read the analog input, so you need some safety margin.
I think you can use up to 32 button/key using this technique. That's give you 150 mV of distance between each button (or +/- 32 for the corresponding analog value.

I would like an answer with a mathematical formula,that
is more enlightening for me and will give me a better
understanding.

And a formula would prove it can be replicated because
its like a proof of reliability

A possible error in your answer is -because you are not being
precise  it may mean that the circuit can't be reliably
replicated (because it may just depend on those specific
resistors used.)

You're just making a voltage resistor divider, with Vin at the top of the string of resistors, Vout at the selected resistor junction, and Gnd at the bottom.
Using 5V as Vin, then
Vout = Vin x (sum of resistance below the junction)/(sum of the entire string).
For example, 10 1K resistors, and the junction is between resistors 5 and 6 (resistor 1, R1, connected to Vin, resistor 10, R10, to Gnd).
Vout = 5V * 5,000/(10,000) = 2.5V
Arduino will return a reading of ~ 2.5V/5V * 1024 = 512 (~4.88mV per step)
Connect between R7 and R8
Vout = 5V * 3,000/(10,000) = 1.5V
analogRead = ~1.5/5 * 1024 = 307


text:
functions not running
I have the following code as part of my efforts to clean this all up into more neatly organised functions.
I'm trying to run GetTemperatures and RunSerial as part of the main loop, however neither are being called.
If I uncomment the two code blocks I've tried to migrate into the functions in the main loop and comment out the calling of those two new functions, everything works ok.
I've looked through the arduino documentation and other places online but I'm unable to see where I've gone wrong.
#include <OneWire.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//#include <DallasTemperature.h>

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

//This sketch is for Wemos R1 not Arduino
//Pin Assignment
OneWire  ds(D6);

//Digital Pin 4 Fan PWM pins)
int FanPin = D7; //Pin 4
int FanPWM = 0; //Start fans at max speed
int FanPercent = 100; // PWM power %

//Temperature thresholds

int Set0PCTemp = 26;   // Temp for 0% fan speed
//int MidTemp = 30;   // Max Temp for Min & Min Temp for Max
int Set100PCTemp = 36;   // Temp for 100% fan speed

// Temperature measurements

float MeasTemp;       //Measured temperature value
float DStemp;         //Value extracted from DS18B20 Sensor

// Serial port input values
int In0PCTemp;
int In100PCTemp;

ESP8266WebServer server(80);

void setup(void)
  {
  //analogWriteFreq(25000);
  pinMode(FanPin, OUTPUT);
  analogWrite(FanPin, 128);
  delay(1000);
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (MDNS.begin("esp8266"))
    {
    Serial.println("MDNS responder started");
    }
    server.on("/", handleRoot);
    server.on("/inline", []()
      {
      server.send(200, "text/plain", "this works as well");
      }
              );
    server.onNotFound(handleNotFound);
    server.begin();
    Serial.println("HTTP server started");
    //wifi end
    }

void handleRoot()
  {
  //declare CSV variables
  String CSVHeaders = "Set0PCTemp,Set100PCTemp,MeasTemp,FanPercent,FanPWM";
  String CSVMessage = "";
  String CSVPayload = "";
  //  Compile CSV variables
  //CSVMessage = Set0PCTemp + "," + Set100PCTemp + "," + MeasTemp + "," + FanPercent + "," + FanPWM;
  CSVMessage += Set0PCTemp;
  CSVMessage += ",";
  CSVMessage += Set100PCTemp;
  CSVMessage += ",";
  CSVMessage += MeasTemp;
  CSVMessage += ",";
  CSVMessage += FanPercent;
  CSVMessage += ",";
  CSVMessage += FanPWM;
  CSVPayload = CSVHeaders;
  CSVPayload += "\n";
  CSVPayload += CSVMessage;
  //  char CSV_Payload[] = CSVPayload;
  //notify serial port of HTTP request
  Serial.println( "Sending Readings");
  Serial.println(CSVPayload);
  server.send(200, "text/plain", CSVPayload);
  }

void handleNotFound()
  {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++)
    {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
    }
  server.send(404, "text/plain", message);
  }

void GetTemperature ()
  {
    Serial.println("step1");
  //original
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float DStemp;
  //////
  if ( !ds.search(addr))
    {
    Serial.println("step2");
    ds.reset_search();
    delay(250);
    return;
    }
  if (OneWire::crc8(addr, 7) != addr[7])
    {
    Serial.println("CRC is not valid!");
    return;
    }
    // the first ROM byte indicates which chip
    switch (addr[0])
      {
      case 0x10:
      type_s = 1;
      break;
      case 0x28:
      type_s = 0;
      break;
      case 0x22:
      type_s = 0;
      break;
      default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
      }
    Serial.println("step3");
    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end
    delay(1000);
    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad
    for ( i = 0; i < 9; i++)
      {
      data[i] = ds.read();
      }
    // Convert the data to actual temperature
    int16_t raw = (data[1] << 8) | data[0];
    if (type_s)
      {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10)
        {
        raw = (raw & 0xFFF0) + 12 - data[6];
        }
      }
    else
      {
      byte cfg = (data[4] & 0x60);
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      }
  DStemp = (float)raw / 16.0;
  }

void RunSerial()
  {
        Serial.print(Set0PCTemp);
    Serial.print(",");
    Serial.print(Set100PCTemp);
    Serial.print(",");
    Serial.print(DStemp);
    Serial.print(",");
    MeasTemp = DStemp;
    //control fan speed
    //if(MeasTemp < Set0PCTemp)
     //{
     // if temp is lower than minimum temp
       //FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 255, 0); // the actual speed of fan
       FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 1023, 0); // the actual speed of fan
       //FanPWM = constrain(FanPWM, 0, 255);
       FanPWM = constrain(FanPWM, 0, 1023);
       analogWrite(FanPin, FanPWM);  // spin the fan at the fanSpeed speed
       //FanPercent = map(FanPWM,0,255,100,0);
       FanPercent = map(FanPWM,0,1023,100,0);
       Serial.print(FanPercent);
       Serial.print(",");
       Serial.println(FanPWM);
       //Serial.println(CSVMessage);
       //}
       //take temperature threshold input
      while (Serial.available() > 0)
        {
        int In0PCTemp = Serial.parseInt();
        int In100PCTemp = Serial.parseInt();
        if (Serial.read() == '\n')
          {
          In0PCTemp = constrain(In0PCTemp, 20, 35);
          In100PCTemp = constrain(In100PCTemp, 35, 50);
          Serial.print("Min=");
          Serial.print(In0PCTemp);
          Serial.print(",");
          Serial.print("Max=");
          Serial.print(In100PCTemp);
          Serial.println();
          Set0PCTemp = In0PCTemp;
          Set100PCTemp = In100PCTemp;
          }
      }
  }

void loop(void)
  {
    GetTemperature;
  //start of GetTemperature content
  /*
  Serial.println("step1");
  //original
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float DStemp;
  //////
  if ( !ds.search(addr))
    {
    Serial.println("step2");
    ds.reset_search();
    delay(250);
    return;
    }
  if (OneWire::crc8(addr, 7) != addr[7])
    {
    Serial.println("CRC is not valid!");
    return;
    }
    // the first ROM byte indicates which chip
    switch (addr[0])
      {
      case 0x10:
      type_s = 1;
      break;
      case 0x28:
      type_s = 0;
      break;
      case 0x22:
      type_s = 0;
      break;
      default:
      Serial.println("Device is not a DS18x20 family device.");
      return;
      }
    Serial.println("step3");
    ds.reset();
    ds.select(addr);
    ds.write(0x44, 1);        // start conversion, with parasite power on at the end
    delay(1000);
    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad
    for ( i = 0; i < 9; i++)
      {
      data[i] = ds.read();
      }
    // Convert the data to actual temperature
    int16_t raw = (data[1] << 8) | data[0];
    if (type_s)
      {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10)
        {
        raw = (raw & 0xFFF0) + 12 - data[6];
        }
      }
    else
      {
      byte cfg = (data[4] & 0x60);
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      }

    //Display current values
    DStemp = (float)raw / 16.0;
    */
    //end of GetTemperature content
    RunSerial;
    //start of RunSerial content
    /*
    Serial.print(Set0PCTemp);
    Serial.print(",");
    Serial.print(Set100PCTemp);
    Serial.print(",");
    Serial.print(DStemp);
    Serial.print(",");
    MeasTemp = DStemp;
    //control fan speed
    //if(MeasTemp < Set0PCTemp)
     //{
     // if temp is lower than minimum temp
       //FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 255, 0); // the actual speed of fan
       FanPWM = map(DStemp, Set0PCTemp, Set100PCTemp, 1023, 0); // the actual speed of fan
       //FanPWM = constrain(FanPWM, 0, 255);
       FanPWM = constrain(FanPWM, 0, 1023);
       analogWrite(FanPin, FanPWM);  // spin the fan at the fanSpeed speed
       //FanPercent = map(FanPWM,0,255,100,0);
       FanPercent = map(FanPWM,0,1023,100,0);
       Serial.print(FanPercent);
       Serial.print(",");
       Serial.println(FanPWM);
       //Serial.println(CSVMessage);
       //}
       //take temperature threshold input
      while (Serial.available() > 0)
        {
        int In0PCTemp = Serial.parseInt();
        int In100PCTemp = Serial.parseInt();
        if (Serial.read() == '\n')
          {
          In0PCTemp = constrain(In0PCTemp, 20, 35);
          In100PCTemp = constrain(In100PCTemp, 35, 50);
          Serial.print("Min=");
          Serial.print(In0PCTemp);
          Serial.print(",");
          Serial.print("Max=");
          Serial.print(In100PCTemp);
          Serial.println();
          Set0PCTemp = In0PCTemp;
          Set100PCTemp = In100PCTemp;
          }
      }
      */
      //end of RunSerial content
      //wifi
      server.handleClient();
  }

Do you know you have to use "()" after the name of a function? Like getTemperature() instead of getTemperature

RunSerial;

that does not call the function. Instead you should do
RunSerial();

same with GetTemperature

Anything you write in C++ is happily accepted by the compiler, even when it make no sense at all. And people thinks that C/C++ is a good choice for learning programming.

Depends on the compiler warning level, of course ... warning: statement is a reference, not call, to function 'getTemperature' [-Waddress]

@JaromandaX. Please, tell me what char (a) = 10; means. That "()" baffles me.

What does that have to do with the code in the question?

Anything you write in C++ is happily accepted by the compiler, even when it make no sense at all. - anything? I doubt it. C++ compilers have been tightening up code validation for a while now.

Please, someone explain me what is the case use for RunSerial; statement. I can't see how this is not an error. Between undefined behavior, implementation dependent features and lack of context free grammar, C++ is a ugly beast.

@LookAlterno simplification of the grammar & semantics, but you can use the identifier of the function on it own to assign to a function pointer: fooPtr = RunSerial;

@ratchetfreak. That I know, but what is the semantic of a reference floating alone in the source code? How can be that not an error?

@LookAlterno it's a nop. you can use (void) var; to silence a unused local variable warning though.

@ratchetfreak Deleting that unused local variable is the right way to do. C++ is feature creep.


text:
3D printer firmware version
Is there a way to determine which version of a Marlin firmware I would have installed onto my printer? I am trying to modify the existing arduino sketch rather than starting all over with a wrong, earlier version. Thanks.

First, check to see if the printer itself yields this information, either on LCD display if present, or by reporting it to a host computer upon connection (ie, try enabling verbose output in your printing software).
While it's not guaranteed to be supported, in practice many Arduino Mega based 3d printers have bootloaders capable of readback of the flashed contents, and the chips themselves are unlocked.  Even if the bootloader does not support this, an ISP connection might.
If you are able to read out the contents, you can have avrdude write them to a flat binary file, and examine it with the strings program or a hex editor.  If you end up with a hex file instead, there are tools for converting this to a flat binary.
Your goal would be to look through the file for version strings, and other messages which might indicate specifics, especially on which side of various points of change or configuration options it falls.
Making such a backup is a good idea before loading a new firmware anyway.  Ideally after verifying that you obtained meaningful contents, you would also readback a few distinct copies of the file and use something like diff to verify that they are all the same.  You can grab the EEPROM contents too, if your firmware may be storing things there.

Thanks. I can see the Marlin fw version in the lcd but not my arduino sketch version/name.

That may well not be saved.  Still, if you have a finite number of candidates you can try to look at details that would differentiate them.  Rebuilding and doing some kind of percentage fuzzy match comparison could work, but could also easily get confused by different compiler versions or build options.

Yeah, that’s what I assumed my option was. Thanks.


text:
Is it possible to extract a hex file via UART from an Arduino?
Right now I am tinkering on my 3D printer that has an Arduino mega as a brain. I need to update the Marlin firmware but in case of an error I want to create an backup of the firmware. And because it is assembled using a shield on top have no access to the ICSP interface. And I was curious if you can extract all the flash and EEPROM via USB (UART). If yes than what software should I use to do that.

AVRDUDE which is used by the IDE to send the content of HEX file from your computer, as a feature letting it to get back the data of the flash, in order to compare and see if data are correct.
For a UNO try:
avrdude -patmega328p -carduino -P/dev/cu.usbmodemFD121 -b115200 -U flash:r:"flash.bin":r

I think it would not be very hard to change that for a Mega.
It works fine. I have use that a lot to debut my "Android Updater" which allow the user of my board to update the code themselves.
PS: Just for info, you'll not get back the HEX file as in the flash, you have only some "pieces" of the HEX file.

When this works, you will in fact get back the contents of the flash. If you have doubts about it, do the process multiple times and diff the result, then examine the actual addresses capture in the hex file.

If you send the code via ISP using the .ino.hex from the Arduino IDE, rather than the ino.with_bootloader.hex, the result is that you will have the code but no more the bootloader. So in this case, you are not able to get back the data using AVRDUDE, of course.

Well, yes, but that has little to do with the question.  If you write with the bootloader and the board is properly configured, you won't loose the bootloader.

Not only is readback supported, avrdude depends on it in order to perform the default verify operation.

It looks like my other answer was completely wrong, so I've deleted it.

Yes, you can read back the flash using the USB interface, as Chris Stratton pointed out, and Peter mentioned in his answer.
The bootloader includes a "verify" action, which means it can be used to read the flash. If you connect up the USB cable to your Atmega2560 you can read the flash back by using a command similar to this:
/usr/local/bin/arduino-1.6.9/hardware/tools/avr/bin/avrdude  `# where avrdude is`  \
-patmega2560     `# chip type: atmega2560` \
-cstk500v2       `# protocol: stk500 v2` \
-P/dev/ttyACM2   `# what serial (hardware) port the board appears on` \
-b115200         `# baud rate` \
-U flash:r:"flash.hex":i   `# save flash as "flash.hex", in Intel format` \
-C /usr/local/bin/arduino-1.6.9/hardware/tools/avr/etc/avrdude.conf  # config file for avrdude

This was done under Linux, with the command in "bash" format, which means the comments look a little strange, as I had to do that to put a comment on each line.
I've put comments on each line to show what each parameter means.
If you happen to have avrdude in your path, or are in the directory where it is installed, the brief form of the command would be:
avrdude -patmega2560 -cstk500v2 -P/dev/ttyACM2 -b115200 -U flash:r:"flash.hex":i -C avrdude.conf

You will probably (almost certainly) have to change the path to where avrdude is, and where the configuration file for avrdude is. You will also need to find out the serial port that the board is on, which you can find out from the Arduino IDE (the Port menu will show you the possibilities).

As Chris Stratton suggests, do this a few times (change the file name of course) and compare the files (eg. using "diff"). If they are all the same then you can be reasonably confident that you have got good copies.

Yes, though it's not a "verify" action of the bootloader, it is explicitly a page read action.  It is avrdude which uses that generic capability to accomplish a verify.


text:
Parse Bluetooth string
I'm developing on android with bluetooth LTE, I can send hex codes, but I send one code at time, so I need to send many informations in this way, how can I recognize a string and save the datas inside an array to parse it later?
Here is my sketch:
 char c=' ';
 String inString,one,check;
 char inData[11];
 char inChar;
 int counter=0;
 bool started = false;
 bool ended = false;
 byte index;

boolean NL = true;
const int LED1 = 6;
const int LED2 = 7;
const int LED3 = 2;
const int LED4 = 3;
const int LED5 = 4;
const int LED6 = 5;

void setup() {
   Serial.begin(9600);
    Serial.print("Sketch:   ");   Serial.println(__FILE__);
    Serial.print("Uploaded: ");   Serial.println(__DATE__);
    Serial.println(" ");

    BTserial.begin(9600);
    Serial.println("BTserial started at 9600");

    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    pinMode(LED5, OUTPUT);
    pinMode(LED6, OUTPUT);

}

void loop() {

  if (BTserial.available()>0)
    {
      Serial.print("bts: ");
      Serial.println(BTserial.available());
      c = BTserial.read();
      check =  String(c, HEX);

      if(check=="ffbc"){
        Serial.println("check");
        index=0;
        while (BTserial.available()>0){

            inChar = BTserial.read();
            check=String(inChar,HEX);
            if(check != "0xfff3")
            {
                inData[index] = inChar;
                index++;
            }
        }
        for (int i=0;i<=11;i++){
          one =  String(inData[i], HEX);
          Serial.print(i);Serial.print(": ");Serial.println(one);
        };

      }

             if(check=="ffca"){
             // Serial.write(c);
              digitalWrite(LED1, !digitalRead(LED1));
             }
             if(check=="ffcb"){
              //Serial.write(c);
              digitalWrite(LED2, !digitalRead(LED2));
              }
              if(check=="ffcc"){
              //Serial.write(c);
              digitalWrite(LED3, !digitalRead(LED3));
             }
             if(check=="ffcd"){
              //Serial.write(c);
              digitalWrite(LED4, !digitalRead(LED4));
              }
              if(check=="ffce"){
             // Serial.write(c);
              digitalWrite(LED5, !digitalRead(LED5));
             }
             if(check=="ffcf"){
             // Serial.write(c);
              digitalWrite(LED6, !digitalRead(LED6));
              }
    }
}

Without the loop I can read all the single datas, but for my job it's not enough, to recognize the data applications I send a "sample string" to recognize the type of informations I want to send.

i think i solved in some way, i send always the same codes at the start and at the end of the datas, so i can racognize the end and then i parse the first element of the destination array. tell  me what you think abou, if it could help someone else:
 if (BTserial.available()>0)
{
  c = BTserial.read();
  check =  String(c, HEX);
  if(check!="fff3"){              // i always start wit an fff3
  inData[index] = c;
  index++;
 }
  else if(check=="fff3"){         //end of data
  index=0;                        //reset the index for the next set of data
  if(String(inData[1], HEX)=="ffbc"){
    Serial.println("read the next 10 data of the array");
    }else if(String(inData[1], HEX)=="11"){
    Serial.println("turn on led 1");
    }

    // for more operations use a switch/case over the if

  }

Why are you using a string to check for the start/end data? You can simply use the hex representation: if(c == 0xfff3). And I'm a bit confused, that you have a 4-digit hex code for one read operation. If you use the SoftwareSerial library as your BTserial object, a call of the read() function returns one byte at a time, so it would be a 2-digit hex code

hi, i'm using the bluetooth nativescript plugin, i don't know why but if i send a character after 9 arduino receives ffxx, (if i send 0xaa, it sends 0xffaa). when i made the first experiments i couldnt understnd the set of characters to parse, so i found the string. for the btserial i use altsoftserial


text:
powering Nodemcu using Vin
Forgive me for this really dumb question. I am an amateur in electronics, and im trying to wrap up my head around this question and im not able to do so. Need your help.
Im trying to power up a nodemcu using a 5v 1A power supply- I connected +ve to Vin and ground to ground. But i see that 5v is not enough to power up the nodemcu. So i removed the 5V and connected to a 9V battery, and again I find the same issue- the power is not enough. Knowing that i did something wrong - i measured the voltage across Vin and ground and find it to be around 2.5V when using the 5v source and around 2.5V when using the 9 V battery too.
Confused and thinking that my nodemcu is corrupted, i ordered a new one, and did the same. But i find that when i try to supply power using Vin, the voltage across the device- Vin and ground is around 2.5V for the newer device also. Obviously Im missing something.
Can anyone tell me what is it that Im doing wrong. Please tell me how to power a nodemcu without using a usb and only using a 5v source.

9V -> Arduino -> VIN -> NodeMCU 5V = dead NodeMCU.

No. the NodeMCU works on USB power still. Its not dead.

Then you're lucky that a 9V battery is one of the weakest batteries around, otherwise it would have killed the NodeMCU.  It's the current you need to consider. The voltage is 5V and must always be 5V. If it seems "too weak", increasing the voltage is a very very bad idea.

The 5v power supply is 1A. So with that too, the NodeMCU doesnt work. Am I missing something here? Please help me.

Did you connect the 5v to the Arduino barrel jack or the USB?

I took a USB charger - 5v 1A and connected its positive to Vin of NodeMCU. I am not using any arduino here.

Which NodeMCU version?

second generation.

What does that mean? NodeMCUs have a version number, not a "generation". What version number is printed on your NodeMCU?

Im sorry. Its V2. I did a google search and found that V2 was called second generation at this blog https://frightanic.com/iot/comparison-of-esp8266-nodemcu-development-boards/.

Ok, that makes more sense - since the earlier boards don't have a VIN pin, they have a 5V pin.

So... you connected the 5V power supply's positive to VIN. Did you connect the power supply's ground to GND?

Yeah, i made the connection as you said sir. 5v to Vin and ground to GND.

why you simple do not google it http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/

I referred it long ago. And followed instructions from there only.

there are different manufacturers

Yeah sir. However, if i follow the connections as outlined in the blog, i think it must work right? But it doesnt work for me? Is there something that i am missing here?

fwiw, i have no trouble doing this with CP2102-based nodeMCUs (amica), but I've never gotten it to work with the larger CH340G lolin boards, which also don't give you 5v out when plugged into USB; useless. Your best bet for those is to get a cheap LDO module (or smps) and power it from any of the 3.3v pins.

Im struggling with the same problem, did you finally manage to fix it? Thanks, Pablo

I have a NodeMCU Esp8266 v3 (Lolin) and it works fine conecting Vin and G to my cell phone power supply rated 5.1V, 1000mA. This develop board has a aprotective diode (the closest to Vin), if you have a Multimeter o multitester you can check it measurement continuity. If your diode is damaged the power applied to Vin never be enough to power up the nodemcu.


text:
Connect NodeMCU (ESP8266) with normal Switch (Regular 1 way Home button)
i am new to these circuit things, i am using Node MCU (ESP8266) board with relay board. To connect to a bulb, but i want to keep my old (one way) switch as it is. Also i want to add internet switching to this button.
How my circuit should look like? Two way switch will be compulsory to use here?  What my circuit should look like? with two way switch and one way switch.
Thank you! (in advance)

Welcome to Arduino SE. Please realize that this is not a free design house, homework-answering service or an on-line technical encyclopedia, copied out to you on demand. People will help you take the next step if your question shows that you've done as much as you possibly could on your own - which your post doesn't. Please revise your question showing your work and findings so far. Or delete the question if Internet searches give you your answer anyway.

are you ok with the light switch being "wrong" if you change it remotely? if so, then just use a relay and have the nodeMCU toggle the relay on switch change, as well as from http. you connect the relay module to GND, VIN, and GPIO 4 or 5. Connect the switch to GND and the other GPIO 4/5, and set the pin mode to INPUT_PULLUP. Connect the AC hot to the relay. done.

First of all, a light bulb works on regular 110 or 230V AC depending on where you live, so directly connecting a wire to, for example, see if the hardware switch is turned on, would fry the NodeMCU. You'll need a relay break-out board that can handle these outputs on the COM/NO/NC (which most of them do) but they usually operate on 5V DC.
A NodeMCU can thus only supply the trigger signal to the relay, you'll need for example a AC to 5V DC power supply (like an iPhone adapter) to power your circuit. The circuit will contain of the relay board (connected with its DC in and out to the adapter and the com port to one of the GPIO's from the NodeMCU) and the NodeMCU itself as the 'brain' of the operation.
I don't exactly know what you mean by 'two-way switch' but the way I'd handle the situation is to wire the switch to the NodeMCU. This means the switch is connected to the 5V power adapter and when the switch is on, the nodeMCU will know because there will be a positive value at one of the GPIO's (whichever you choose). You can then also handle both commands from a server and the switch itself.
I'm doing kind off the same thing here with a NodeMCU working as a garageport opener with MQTT communication to a Homebridge server and MQTT broker running on a Raspberry Pi. If you want the code (still work in progress though) let me know ;)
EDIT
Here is the schematic you asked for. not the prettiest thing but it should make things clear. Let me know if you have any more questions!

simulate this circuit – Schematic created using CircuitLab
-BM

Hello, thank you for great explanation, but i want to know the circuit diagram. Is that possible from your side.
I am using proper system as your mentioned. But i am not getting the circuit connections to connect the switch from relay to bulb. Can you help me with its suggestion?

I edited the answer with a schematic for you @user3201500

OK sure i will check and revert you soon.

That's not exactly "keeping the old switch as it is" - However, to keep the old switch, as long as it's a "two-way" switch, then, yes, you can keep the old switch, but you still have to make a minor change to it's wiring - and then wire in the relay

@JaromandaX Yea, I know... but there is no other way to let the NodeMCU have full control over the circuit. If you wanna attach an app to the system which controls the lights and if you just wire in the relay to the existing circuit, then when the power switch is flicked, the NodeMCU would not know about it. You have to have a input which signals the nodemcu that the switch is flicked. It's better this way, trust me I'm an engineer :D

Indeed, I see your point. I guess either way would require some rewiring anyway, so your solution is ideal


text:
Arduino MEGA 2560 - PWM in case statements not working
So I am using Arduino to control RGB Strip light, the analogueWrite(Pin,Value); Works with the prebuilt AnalogueWriteMega example - on pins 8, 9, and 10.
When I move this into my program, Pin 8 still works but pins 9 and 10 don't work.
Anywhere I write analogueWrite() it only works if the value is 255

Green is pin 8
Red is pin 9
Blue is pin 10

#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>

#include <LiquidCrystal.h>
// encoder
int val;
int encoder0PinS = 29;
int encoder0PinA = 31;
int encoder0PinB = 33;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;
int MenuPos;
int SubPos;
bool Selected = false;
int Reader = LOW;

// lcd
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//pot
int ASensePin = A0;
double ASenseValue = 0;
double AFixedValue = 0;
int AFixOut = 0;

//randoms
int ranPin;
int ranVal;

//IR

int receiver = 45; // Signal Pin of IR receiver to Arduino Digital Pin 45

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'

void translateIR() { // takes action based on IR code received

  // describing Remote IR codes
  switch (results.value)
  {

    case 16195807:
      Serial.println("Red, 0, 255, 0");
      analogWrite(8, 0);
      analogWrite(9, 255);    < ------ works
      analogWrite(10, 0);
      break;

    case 16197847:
      Serial.println("Yellow, 255, 255, 0");
      analogWrite(8, 100);      < ----don't work
      delay(50);
      analogWrite(9, 100);       <----don't work
      delay(50);
      analogWrite(10, 0);
      break;

    case 16228447:
      Serial.println("green, 255 , 0, 0");
      analogWrite(8, 255);
      analogWrite(9, 0);
      analogWrite(10, 0);
      break;

    case 16230487:
      Serial.println("turquois, 0, 255, 255");
      analogWrite(8, 0);
      delay(50);
      analogWrite(9, 100);
      delay(50);
      analogWrite(10, 100);
      delay(50);
      break;

    case 16212127:
      Serial.println("blue, 0, 0, 255");
      analogWrite(8, 0);
      analogWrite(9, 0);
      analogWrite(10, 255);
      break;

    case 16214167:
      Serial.println("Purple, 255, 0, 255");
      analogWrite(8, 100);
      delay(50);
      analogWrite(9, 0);
      delay(50);
      analogWrite(10, 100);
      delay(50);
      break;

    case 16244767:
      Serial.println("White, 255, 255, 255");
      analogWrite(8, 255);
      analogWrite(9, 255);
      analogWrite(10, 255);
      break;

    default:
      Serial.println(results.value);
  }// End Case

  delay(500); // Do not get immediate repeat
} //END translateIR

void setup() {
  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  pinMode (encoder0PinS, INPUT);
  pinMode (8, OUTPUT);
  pinMode (9, OUTPUT);
  pinMode (10, OUTPUT);

  lcd.begin(16, 2);
  lcd.print("      Start     ");

  Serial.begin (9600);
}

void loop() {
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      encoder0Pos--;
    } else {
      encoder0Pos++;
    }
  }
  encoder0PinALast = n;
  if (encoder0Pos == 4) {
    encoder0Pos = 0;
  }
  if (encoder0Pos == -1) {
    encoder0Pos = 3;
  }

  MenuPos = encoder0Pos;

  Reader = digitalRead(encoder0PinS);
  // Serial.println(Reader);

  if (digitalRead(encoder0PinS) == LOW) {
    while (digitalRead(encoder0PinS) == LOW) {}
    Selected = true;
  }

  Serial.println("MenuLoop");
  switch (MenuPos) {
    case 0:
      lcd.setCursor(0, 0);
      lcd.print("     Random    ");
      while (Selected == true) {
        ranPin = random(8, 10);
        ranVal = random(0, 255);
        analogWrite(ranPin, ranVal);

        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }
      break;

    case 1:
      lcd.setCursor(0, 0);
      lcd.print("       IR      ");
      Serial.println("IR Receiver Button Decode");
      irrecv.enableIRIn(); // Start the receiver

      while (Selected == true) {
        if (irrecv.decode(&results)) // have we received an IR signal?
        {
          translateIR();
          irrecv.resume(); // receive the next value
          lcd.setCursor(0, 1);
          lcd.print("               ");
          lcd.setCursor(0, 1);
          lcd.print(results.value);
        }
        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }

      break;

    case 2:
      lcd.setCursor(0, 0);
      lcd.print("      Temp     ");
      break;

    case 3:
      lcd.setCursor(0, 0);
      lcd.print("      Pot      ");

      while (Selected == true) {

Not working
        for (int thisPin = 8; thisPin <= 10; thisPin++) {
          // fade the LED on thisPin from off to brightest:
          for (int brightness = 0; brightness < 255; brightness++) {
            analogWrite(thisPin, brightness);
            delay(2);
          }
          // fade the LED on thisPin from brightest to off:
          for (int brightness = 255; brightness >= 0; brightness--) {
            analogWrite(thisPin, brightness);
            delay(2);
          }
          // pause between LEDs:
          delay(100);
        }

        if (digitalRead(encoder0PinS) == LOW) {
          while (digitalRead(encoder0PinS) == LOW) {}
          Selected = false;
        }
      }
      break;
  }
}

The problem has nothing to do with your switch code. It's all to do with what you are trying to do, and peripherals conflicting.
Simply put: both PWM on pins 9 & 10, and the infrared library, require exclusive use of Timer 2.
Only one can use it. Either the infrared library, or PWM on those two pins, but not both.
You can modify the IR library to use a different timer instead of Timer 2 - for instance, you can set it to use Timer 1 which will remove your ability to use pins 11 and 12 as PWM.
This is the bit of code that you would need to find and modify on your system to change timers.  This page shows you which timers are used for PWM on which pins.

Thanks this worked, I swapped pins 9 and 10 to 6 and 7 so they where not clashing with the timer from IR.

An other option is a software pwm library. There are a few of those. They require a timer (which is not used by something else). The software pwm can be on any pin, because the pwm is done in software in the interrupt.


text:
Powering Arduino Uno and Ardumoto Motor Driver Shield
I need to power an Ardumoto Shield to drive two 12V DC motors. I was planning to connect a 12V battery to the Max 18V input on the Ardumoto and a 9V battery to the barrel jack input of the Arduino Uno.  Can you tell me if this should be ok or if it would cause any damage to the Arduino?
It mentions in the Ardumoto hookup guide:

There's no mention of the Max 18V input on the Ardumoto.. Advice appreciated, thanks.

Do not supply power to both the Arduino barrel jack input and VIN on the shield!

There goes the simple answer. Choose one.
If you power the system through arduino barrel jack input, you will have polarity protection, but the voltage output on VIN pin (which also used by Ardumoto shield) is slightly lower, about 0.6V lower than the input voltage because of the voltage drop on the protection diode.
If you have want to differentiate the supply for Ardumoto and Arduino (as described on your plan), you have to tamper the Ardumoto shield to isolate both supply. Although I never try it myself, it seems possible if you understands how L298 works.

I'll probably just use the 18V Max Vin on the Ardumoto shield.  Or maybe get rid of the Vin header pin on the Ardumoto that connects to the Arduino Vin.

The L298 used in the Ardumoto shield has a maximum supply voltage of 46V. Hence 18V should be sufficient to power it as long as the motors have enough power too.
The Arduino voltage regulator, on the other hand, won't be able to handle such a high voltage. Hence you will have to remove the Vin pin that connects the Arduino & the shield in order to isolate the power supplies of the two.
Only then should you attempt plugging in the shield & then powering the Arduino through the 9V battery.