text:
Write to serial only if the state of a light sensor changes
I need to know the times when an LED strip turns on and turns off.  The LED switch is driven by light dependent resistor.  When the sun goes down the LED strip turns on. This is all happening on a circuit that I did not create nor is it Arduino driven.  I need to know the times (in local time) that the LED turns on and off.  I have another light dependent resistor near the LED strip and I am using the Arduino Uno to print to the serial monitor its state every second.
I can listen to the serial port via Python and record the seconds via Python.  No worries
What I would like to do is have the Arduino code print to the serial monitor only if the state of the LED changes.  For example, when the LDR turns on the LED strip, Arduino prints to the serial monitor once, then in the morning when the LED goes off, print to the serial monitor once.  I am having trouble figuring out the code to do that.  The LDR is not like a button since it is always reporting back analog data.    Any help is appreciated.

You need to keep track of the previous value and compare the current value to that. (It may work better to keep track of the last few dozen previous values and compare the averages of, e.g., the last dozen to the dozen before that.) Does this help you try to write some code that you could put into your question for us to help you further with?

Ditto.  Especially the idea of taking multiple readings before deciding it is a for-real change and not just a glitch.

You wrote: “I am using the Arduino Uno to print to the serial monitor
its state every second.” This is exactly the right thing to do. Make a
record of the analog readings for a few days, then plot the readings as
a function of time.
Once you have a nice plot, take a close look at it. You should be able,
by reading the plot, to decide on a threshold value that you can use to
tell whether the LEDs are on or off. Or, better yet, two thresholds in
order to have some hysteresis.
Then you can write something like this:
const uint8_t LDR_PIN = ...;
const uint16_t THRESHOLD_LOW = ...;
const uint16_t THRESHOLD_HIGH = ...;

uint8_t state = LOW;

void loop()
{
    uint16_t reading = analogRead(LDR_PIN);
    if (state == LOW && reading >= THRESHOLD_HIGH) {
        Serial.println("Reading is now HIGH.");
        state = HIGH;
    } else if (state == HIGH && reading < THRESHOLD_LOW) {
        Serial.println("Reading is now LOW.");
        state = LOW;
    }
}

+1 for the hysteresis -- it quickly handles the debouncing since it will trigger once on the first observation above the threshold, and won't reset until it is definitely lower.

If you have already set the resistor to print to Serial every second, then it is simple to modify. Your code is probably like this:
void loop() {
// something something
Serial.println(analogRead(resistorPin));
// other other
}

and you want something like this:
int lastValue,newValue;
int treshold=200; // or some other empirical value,
// analogRead() returns 0..1024, so it should be safely inside
void loop() {
// something something
newValue=analogRead(resistorPin);
if (newValue-lastValue > treshold) {
    Serial.print("Value increased to ");
    Serial.println(newValue);
    lastValue=newValue;
    };
if (lastValue-newValue > treshold) {
    Serial.print("Value decreased to ");
    Serial.println(newValue);
    lastValue=newValue;
    };
// other other
}

the treshold value should be set so the event is triggered if substantial change in value happend (so probably those LEDs went on/of) but not trigger when there is a smal change (like cloud going on sky).
Eventually you can also print the time, at which the event happened, using something like http://playground.arduino.cc/Code/DateTime or http://playground.arduino.cc/Code/Time or any other library suiting your needs. You may also consider to use some real time module like https://www.pololu.com/product/2770 or https://www.adafruit.com/product/264 or https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/overview or any other RTC module you like/have.

Python datetime module can also be used to timestamp the events, this will eliminate the need for syncing or using external RTCs.

An LDR doesn't have a "state", being a resistor that varies continuously, and inversely with the light intensity. The LED strip has distinct states: lit and not lit. It sounds like you want your code to deduce the LED state from the sensor value. You'll need to define lighting states based on the the LDR readings, and those readings won't be consistent; they'll vary from measurement to measurement of the same lighting conditions and they'll be affected by changes in the ambient lighting. If you can exclude ambient light falling on the LDR, the job will be easier. @Edgar_Bonet described a way to ranges of LDR readings corresponding to 'lit' and 'not lit'
When a moving average of LDR readings, or some number of consecutive LDR readings falls within the range contrary to the state your code been keeping for the LED lighting, it should change the state and print.
If ambient lighting changes are unavoidably affecting the LDR, you'll definitely need to keep some sort of moving average and watch for a large difference between a small number of averaged readings and the longer-term moving average used to correct for ambient. This is a kind of auto-zeroing and it can lead to its own errors: sensing the room lights being turned on or off, cloud shadows, or a person or animal passage throwing a shadow, can all cause false change-of-state detection.
Update:
I'd add that you might compare the LDR output to 3 ranges: [0 - MAXDARK], [MINLIGHT - 1023], and "neither" - the gray zone in between. This is analogous to how the digital input-pin receivers in the MUC decide whether a digital signal (which is inherently analog) is HIGH or LOW. You'll have to experiment with the values of MAXDARK and MINLIGHT to find the right values for your environment.
Then you you'd print, once, whenever the LDR signal solidly enters either the MAXDARK or MINLIGHT zones, and not again until after the signal has solidly exited that zone, or equivalently, solidly entered the gray zone.
"Solidly" is probably something like NCONSECUTIVE averaged samples. Again, you'll have to find a value for NCONSECUTIVE that is both reliable and responsive. Too low a value may give you several time-stamps for the same event; too high a value will delay how quickly you detect the event (which might be totally irrelevant for a twice-a-day event).

I need to know the times (in local time) that the LED turns on and off. .. I am having trouble figuring out the code to do that.

simple.

attach a pin to the circuit's output that turn on / off the led.
set up your arduino to read the state or state changes of that pin. this can be done via interrupts or polling.
based on the state of the pin, determine if the led is on or off, and record the current time.

step #1 can be done with light sensors (on the led's light output). but that can be slightly trickier.

The LDR is not like a button since it is always reporting back analog data.

you can set up the ldr to read it like a button.


text:
Can I make delayMicroseconds more accurate?
I'm trying to bit bang DMX data and that requires 4us pulses. Not having much luck with the results I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.
Here's a quick little test I did:
unsigned long ptime;

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

void loop() {
  ptime = micros();
  delayMicroseconds(4);
  Serial.println(micros() - ptime);

  delay(1000); //just to keep the serial monitor from going nuts
}

And the results:

8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

I was kinda shocked at just how bad it's accuracy is. It's double the time I wanted to delay, but it's not even consistent to where I could just divide by 2!
Is there anything I can do to get correct, consistent results?

Why are you bit-banging instead of accessing the UART directly?

So I can have more than one output.

The Mega has four UARTs. Even if you hold one permanently for programming that still gives you three universes.

I'm just testing with the mega because that's what I currently have available, the final project will have an ATMEGA328

The ATmega328PB has two UARTs.

Also, bit-banging more than one serial port, especially at 250kbps, needs more grunt than any AVR has.

micros() has a resolution of four microseconds.

The problem here is how you measure.

As explained in the previous answers, your actual problem is not the
accuracy of delayMicroseconds(), but rather the resolution of
micros().
However, to answer your actual question, there is a more accurate
alternative to delayMicroseconds(): the function _delay_us() from
the AVR-libc is cycle-accurate and, for example
_delay_us(1.125);

does exactly what it says. The main caveat is that the argument has to
be a compile-time constant. You have to #include <util/delay.h> in
order to have access to this function.
Note also that you have to block the interrupts if you want any kind of
accurate delay.
Edit: As an example, if I were to generate a 4 µs pulse on PD2
(pin 19 on the Mega), I would proceed as follows. First, notice that the
following code
noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

makes a 0.125 µs long pulse (2 CPU cycles), because that's the
time it takes to execute the instruction that sets the port LOW. Then,
just add the missing time in a delay:
noInterrupts();
PORTD |= _BV(PD2);   // PD2 HIGH
_delay_us(3.875);
PORTD &= ~_BV(PD2);  // PD2 LOW
interrupts();

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

Your test results are misleading.  delayMicroseconds() actually delays fairly precisely (for delays of more than 2 or 3 microseconds).  You can examine its source code in file /usr/share/arduino/hardware/arduino/cores/arduino/wiring.c (on a Linux system; or on some similar path on other systems).
However, the resolution of micros() is four microseconds. (See, eg, the garretlab page about micros().) Hence, you will never see a reading between 4 microseconds and 8 microseconds.  The actual delay might be just a few cycles over 4 microseconds, but your code will report it as 8.
Try doing 10 or 20 delayMicroseconds(4); calls in a row (by duplicating the code, not by using a loop) and then report the result of  micros().

With 10 delays of 4 I'm getting a mixture of 32's and 28's... but 4*10 = 40.

What do you get with, say, 10 delays of 5 ?  :)  Also note, for bitbanging you might need to use fairly direct port accesses, ie, not digitalWrite(), which takes several microseconds to execute.

40 & 44... But shouldn't it be rounding up? What am I missing here?

By  “rounding up” do you mean delayMicroseconds() ? I don't see that as any better than rounding down.  ¶  Regarding the source of inaccuracy, if the routine gets inlined then timing depends on surrounding code.  You could read assembly or disassembly listings to see.  (See  “Making assembly listings” section in my answer to question Equivalent for PORTB in Arduino Mega 2560, which may anyway be relevant to your bitbanging project

I'm checking to see how good the Arduino is at delaying... Seems to be pretty terrible at it.

micros() has a well-documented resolution of 4 µs.
You could improve the resolution by changing the prescaler for Timer 0 (of course that throws out the figures, but you can compensate for that).
Alternatively use Timer 1 or Timer 2 with a prescaler of 1, which gives you a resolution of 62.5 ns.

 Serial.begin(9600);

That's going to be slow anyway.

8 4 8 4 4 4 4 4 8 8 8 8 4 8 8 4 4 8 4 4 4 8 8 8 4 8 4

Your output is exactly consistent with the 4 µs resolution of micros() coupled with the fact that sometimes you would get two "ticks" and sometimes one, depending on exactly when you started the timing.

Your code is an interesting example of measurement error. delayMicroseconds(4); will delay for close to 4 µs. However your attempts to measure it are at fault.
Also, if an interrupt occurs then it will stretch the interval a bit. You need to turn interrupts off if you want an exact delay.

When measured with an oscilloscope, I found that:
delayMicroseconds(0) = delayMicroseconds(1) = 4 μs real delay.
So, if you want a 35 μs delay you need:
delayMicroseconds(31);

Is there anything I can do to get correct, consistent results?

The Arduino implementation is quite generic thus may not be as effective in some applications. There are a few ways for short delays, each with its own shortfalls.

Use nop. Each is one instruction so 16th of a us.
Use tcnt0 directly. Each is 4us as the prescaler is set to 64. You can change the prescaker to achieve 16th us resolution.
Use ticks, you can implement a clone of systick and use it as basis of the delay. It offers finer resolution plus accuracy.

edit:
I used the following block to time the various approaches:
time0=TCNT0;
delay4us();             //65
//t0delayus(4*16);          //77
//_delay_us(4);             //65
//delayMicroseconds(4);     //45
time1=TCNT0 - time0;        //64 expected

before that, I had reset the timer0 prescaler to 1:1 so each TCNT0 tick is 1/16th of a microsecond.

delay4us() is built up from NOP(); it produced a delay of 65 ticks, or just over 4us;
t0delayus() is built up from timer0 delays. it produced a delay of 77 ticks; slightly worse than delay4us()
_delay_us() is a gcc-avr function. performance on par with delay4us();
delayMicroseconds() produced a delay of 45 ticks. the way arduino implemented its timing functions, it tends to under-count, unless in an environment with other interrupts.

hope it helps.

Note that the expected result is 65 ticks, not 64, because reading TCNT0 takes 1 CPU cycle.

source: Stack Exchange

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

sort: votes


text:
Simplifying code, getting invalid conversion from 'const char*' to 'char*'
I have a program that does 4 times the same thing with different parapmeters; and was trying to simplify my code to take one parameter as a variable.
Example (what was):
const char MQTT_PUB_IRRIGATION_TANK_VALVE[]      = "ArgyleCourt/Property/Hub/IrrigationTank/Valve";
const char MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE[] = "ArgyleCourt/Property/Hub/HouseBoreWaterTank/Valve";

publishTankValveStatusIrrigation(false);

void publishTankValveStatusIrrigation(bool demandStatus) {
  if (demandStatus) {
    mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "ON");
  } else {
    mqttClient.publish(MQTT_PUB_IRRIGATION_TANK_VALVE, "OFF");
  }
}

publishTankValveStatusHouse(false);

void publishTankValveStatusHouse(bool demandStatus) {
  if (demandStatus) {
    mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "ON");
  } else {
    mqttClient.publish(MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE, "OFF");
  }
}

to one function now passing the topic also inot the function, thus needing only one function:
publishTankValveStatus(false, MQTT_PUB_IRRIGATION_TANK_VALVE);
publishTankValveStatus(false, MQTT_PUB_HOUSE_BOREWATER_TANK_VALVE);

void publishTankValveStatus(bool demandStatus, char topicToPublishTo) {
  if (demandStatus) {
    mqttClient.publish(topicToPublishTo, "ON");
  } else {
    mqttClient.publish(topicToPublishTo, "OFF");
  }
}

when I compile the simplified function, I get "warning: invalid conversion from 'const char*' to 'char' [-fpermissive]", but do neither understand why or how to fix it.

The function declaration
void publishTankValveStatus(bool demandStatus, char topicToPublishTo)

declares topicToPublishTo as a char, that is, as a single character instead of as an array of characters that is constant.
Change char to const char * to say that  topicToPublishTo is an array of characters that is constant.

Thanks! Works :) You wrote const char *; is it permissible or good practice or even the same to write const char* ? This C business with single char, many char, and pointer really trips me all the time :(

@MaxG, both forms are ok; which to use is mostly personal preference. I think const char*, with the star close to char,  is used much more commonly than with a space between.  But if you are declaring several variables on one line (which some may frown on) it makes sense to associate the star with the variable name.  Eg, in char *a, b, *c, d, e;, only a and c are pointers vs. single characters.  Also, for the parameter declaration, some would say const char topicToPublishTo[] instead of const char *topicToPublishTo

Also see answers to  const char * const versus const char *?, which cover examples like char* astring, const char* astring, char* const astring, and const char* const astring.  Note, answers to  What is the difference between char * const and const char *? might be more understandable.

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


text:
How do I sense that the serial monitor is started?
When starting the serial monitor in IDE I want to save important data to EEPROM before the Arduino Uno restarts. I do not have physical access to the Arduino so a "press button" solution does not work here.

You can't. There is no way of detecting if the serial monitor is open or not.
However, you can disable the automatic reset and provide some functionality in your code for saving data to EEPROM when prompted through a command entered on the serial monitor (if you now need to even save the data).

you did it again.  That is a very cool trick.  Thank you for teaching me that one.  I don't understand how the 120 Ohm value was figured out, but this is something I will put in my mental toolbox for sure.  Kudos.  Upvote.

What you really want to do is to store the data before the computer shuts down.
Here is what I did.
 I am running a Mega in a car and using it for a lot of things.  The Mega receives its power from the ignition switch.  When the ignition switch it turned on, the Mega boots up.  In the "setup" section of the program, I set a digital output HIGH.  The digital output is tied to the coil of a relay.  One side of the relay is tied directly to the battery.  Once the relay is energized, the relay supplies power to the Mega.  I have a digital input tied to the power coming from the ignition switch through a resistor and a zener diode to clamp the voltage at 5 volts.  In the main program I monitor the input power digital input.  When I see the power go down,(ignition switch is turned off), I run a Shutdown program that stores all of the data I need stored to the EEProm.  Once that is done, I set the digital output LOW.  This de-energizes the relay and removes the power from the Mega.  If you push the reset button, that is a hardware reset and you lose your data.  If I want to reset the computer, I simply run the "Shutdown" routine. I can do that using a remote switch that drives a digital input.


text:
Cannot locate Rx Tx pins on SIM800a GSM module
I recently bought a SIM800a GSM module in India and I am unable to find the Rx Tx pins of the module to make calls using a Arduino duimilanove.
The main problem is also that I can't find the data sheet for Sim800a in the net so that I can use a multi meter to determine the Rx Tx pins.
Here are some screenshots of the module-

There is no label showing Rx Tx here. There is I2C protocol(SCL,SDA) but I dont know how to code in Arduino for making a call using I2C.
I found a SIM800a picture on ebay with labels(not the data sheet) but when I tried using the pins in that manner it did not work. The SIM800a I have is connected to the network as the network led blinks after 3 sec and when I call it then the alarm rings. But it is unable to transmit calls or sms.

This is the code I am using. I remove the Rx Tx pins before uploading the code and immediately put them after uploading.

char phone_no[]="9953642386";
void setup()
{
Serial.begin(9600);  //Open Serial Connection at baudrate 9600
delay(5000);
Serial.println("AT"); // Wake up GSM
Serial.print("ATD"); //Dial the phone number using ATD command
Serial.print(phone_no);
Serial.println(";"); // Semicolon is a must at the end
delay(5000);
Serial.println("ATH"); // After a delay of 5 secs Hang the call
}
void loop()
{
// empty loop.If you enter the above code here,the call will be made FOR EVER repeatedly.
//Take Caution while coding under loop.At some condition you’ve to terminate the Call
}

Otherwise is it possible to use the SDA and SCL pins for this purpose of calling to a phone from the gsm module ?
Any help would be appreciated.

This datasheet may help you.  On page 14 you can see TXD and RXD are pins 9 and 10.
Orientation is hard to determine, but it appears that pin 1 is where the most red on the label is.

You should now be able to trace where those pins go to. They look like they go to high numbered pins, around the 11/12 area.

Thanks found the pins :) didnt realize the data sheet of sim 800a and sim 800 will be the same


text:
Reading Arduino serial data in Octave on Mac
I am trying to read serial port data generated by Arduino in Octave on Mac. I installed and loaded the instrument-control package for the same. I used this piece of code to check if the package was installed properly
if (exist("serial") == 3) disp("Serial: Supported") else disp("Serial: Unsupported") endif

I do get an output saying Serial: Supported.
I am following the tutorial here for step by step guidance.
I next use s=serial('portname') to create a serial port object. However, I am not sure what name to use instead of COM5 on Windows for Mac.
I checked and my Arduino is connected to cu.usbmodem1421 so I tried following 3 options a)cu.usbmodem1421 b) usbmodem1421 c)1421 but in each case I get an error saying "serial: Error opening the interface: No such file or directory".
Could anyone tell me what port name I can use or if there are any suggestions for the big picture problem as to how to read Arduino serial data in Octave (on Mac)? Thanks for the help in advance.

You most likely need the full canonical pathname for the port:
/dev/cu.usbmodem1421

On the Mac, as in Linux and other Unix derivatives, most devices, serial ports included, are special files in the /dev directory.

Thanks for the suggestion. I tried /dev/tty.usbmodem1421 and it worked!

According to the rules of TTY naming for connecting to an external device from inside the Mac you should use the /dev/cu.* variant. It's the same physical devices as the /dev/tty.* variant, but the line control is handled differently. The /dev/tty.* variant is intended for incoming connections to the Mac (a text-based login prompt).


text:
Using Lego temperature sensor with Arduino
I have Arduino mega and Lego temperature sensor which I would like to connect to the Arduino. I'm trying to use a I2C connection between them, with no luck. I connected the sensor and Arduino referring to the picture below:
I'm using the Wire library for transmitting data. This is my code currently:
#include < Wire.h >
byte ADDRESS=0x98;
byte CONFIG=0x01;
void setup(){
  Serial.begin(9600);
  Wire.begin();
  Wire.beginTransmission(ADDRESS);
  Wire.write(CONFIG);
  Wire.endTransmission();
  delay(100);
}
void loop(){
  Wire.beginTransmission(ADDRESS);
  Wire.write(CONFIG);
 Wire.endTransmission();
  Wire.requestFrom(ADDRESS,2);
  delay(100);
  int avail=Wire.available();
  Serial.println(avail);
  delay(100);
}

I found the config and address values from RobotC drivers for the same sensor. But all I get is zeros. Is there any way i could check for a defect sensor? Is my code correct?

Start with a i2c scanner : http://playground.arduino.cc/Main/I2cScanner

Looks like this is the datasheet for the actual sensor http://www.ti.com/lit/ds/symlink/tmp275.pdf. Reading that and cross referencing with the header file you liked to, should explain how to communicate with it.

I2C scanner helped me to use the correct address, which was different from the one in drivers. Now my sensor is working. Thank you, Jot!

I managed to get it work with the following code:
float getTemp(){
    #define ADDRESS 0x4C
    #define CONFIG 0x00
    float temp;
    Wire.beginTransmission(ADDRESS);
    Wire.write(CONFIG);
    Wire.endTransmission();
    delay(50);
    Wire.requestFrom(ADDRESS,2);
    temp=Wire.read();
    if(Wire.read()==128){
        temp+=0.5;
    }
    return temp;
}

And connect the green wire to 3.3V, not to the 5V.


text:
Conditional compilation, how to determine whether a variable has been declared?
Whilst using #if/#end constructs, how can I determine whether a specific variable has already been declared?,
e.g.,
#if [the variable "pinname" has been declared]
Serial.print(F("Pin name: "));
Serial.println(pinname);
#end

If this question has been addressed, I cannot find a reference for it.

Normally you use the "#ifdef" directive.
The opposite is "#ifndef".
For example, if you only wanted to include variable definitions once many use this pattern for a header file named, say, "my_variables.h":
#ifndef MY_VARIABLES_H
#def MY_VARIABLES_H

int counter;
bool flag;

#endif

In this way, no matter how many times you include this file, you only define the variables once.  Because after the 1st time the compiler sees this file, the variable MY_VARIABLES_H is defined and the subsequent time the compiler sees this file, the compiler will skip over the variable defines.

You cannot. Simple as that.
I suspect this is an XY Problem. If you edit your post stating what you're actually trying to do, I'll edit my answer (or delete it if I don't know).

my example is exactly what I am trying to do.
@Mark Smith, In this case, specific variables and names are defined based on board attributes.  Another routine is attempting to display such, but obviously only for defined variables.  Of course, I can handle this with the necessary book-keeping.  However, I'd like to know if there is a simpler solution.  If not, I know exactly how to get the results i want.


text:
ESP8266 unstable connection
I try to flash an ESP12E microcontroller through an FTDI serial converter. It seems like the UART connection is a bit unstable, because when I try to flash it via esptool it often throws "Timed out waiting for packet header" error. Also when I thy to get the flash_id the same error occures at around 50% of the time. The simplier commands like get_mac and chip_id are working well.
I'm using an ESP module with wires soldered to its pads. It is put into a breadboard and it's connected to a USB-UART converter via jumper wires.
What could be the problem?

I have several 4 x ESP07's, 2 x ESP12E's and 14 x ES12F's ... the 07's and 12F's never give me problems, however, the two 12E's are unstable as hell when using FTDI, even flashing OTA whilst powered by FTDI cable is a 50/50 proposition - ditch the 12E's get some 12F's is my advice

Power supply...
I designed a pcb for the ESP module, it works like a charm since then. Used a TC1262 regulator, a 100n ceramic and a 1000u electrolyte capacitor (maybe 100u would have been enough) very close to the Vcc and GND pins.
Seems like the ESP is really sensitive to the power supply stability.


text:
Capacitor Questions
I've designed a board (HAT) that uses the ATmega328P microcontroller, and I think I might have made some mistakes in the board design. The design is most like the Arduino Pro mini, but with a 5A dual channel H-bridge, running at 3.3V 16MHz, and using the Raspberry Pi as the power source.
My Board: https://github.com/cescalemodels/BaseStationHAT/tree/master/Hardware
Arduino Pro Mini: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
1) Do I have to have C3? I think it's for power stability and needs to be put next to the microcontroller, but I'm really not sure and want to eliminate it as a possibility as to which part made the board fail.
2) Do I need C2 if I'm not using the DTR Pin?
3) I assume that I don't need C13 and C10 because I'm getting power from the Pi, but can someone confirm?
If it helps, when I boot the raspberry pi, the serial port comes up, but I am totally incapable of communicating. Are there other components that I'm missing?

The 16MHz at 3.3v is the most likely candidate for failure...

Capacitors are important, but I would atleast put the mounting holes/pads on your design and then just check if it works well withouth mounting the capacitors. If possible, monitor the voltage with a scope, to see if it dips when, for example, powering on the motors. But it's unlikely that they are the cause of the failure.

Every active chip should have adequate decoupling. That is the point of C3, to provide decoupling for the MCU. It is required.
While you don't need capacitors on the output of a non-existent regulator you do need a reservoir capacitor on the power input to your board. 10uF should be adequate.
No, you don't need the DTR capacitor if DTR is not connected to anything.
All that aside, there are two fundamental flaws I can see:

The raspberry pi can only provide something like 50mA on the 3.3v supply. (Or originally anyway, it may have improved with newer versions)
The ATMega chip cannot run reliability at 16MHz from just 3.3v. 10MHz is your top limit IIRC.

I didn't see any circuit in the links (just 5 files, which may or may not have been circuits). The PI B+ and later can supply 800mA from 3.3V, and ATmega328P will run at 12MHz on 3.3V (as used on Gertboard), although this is marginal according to the data sheet.

@Milliways That's good re: the 3.3V. When the original board came out more 3.3V current was one of the many items on my list of recommendations to Eben. It seems that's the only one he took on board ...


text:
Arduino pins always reading HIGH (1)
I have tried changing pinModes and I/O declarations but still getting erratic or unexpected pin readings (HIGH), even though, I think, that I have set them LOW during setup. I read elsewhere that this is not uncommon, but I have not found a similar situation or a suitable explanation/solution. I can only believe that it is a basic misunderstanding (still learning). Thanks for any support. By the way, I had deleted the use of the keypad for trial purposes. My code is below:
//////////////////////////// Initialize & Includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;
boolean pir_SensorPin = 2;
int led_OutPin = 11; // green
int alarm_OutPin = 12; // red
int alarm_count = 0;
boolean switchPin = 4; // alarm on test
boolean keypadPIN;
int z = 0;
int i = 0;
int waitTime = 5000;

//////////////////////////// Setup Keypad //////////////////////////
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// Setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (switchPin, INPUT);       // Set pinMode.
  pinMode (led_OutPin, OUTPUT);     // Set pinMode.
  pinMode (alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (pir_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (led_OutPin, LOW);   // Set output pins to LOW for start.
  digitalWrite (alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (switchPin, LOW);
  digitalWrite (pir_SensorPin, LOW);
  Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (led_OutPin, HIGH);
  }
  //  attachInterrupt (digitalPinToInterrupt (2), trigger, CHANGE); // PIR as interrupt
  Serial.println ("System Ready");

}

//////////////////////////// State Setup //////////////////////////
enum STATE {
  armed, // system acknowledges trigger
  unarmed, // system unarmed via keypad entry setting keypadPIN = LOW
  justActivated, // PIR-triggered
  alarm // confirm system unarmed then goto unarmed state else start alarm
};

STATE systemState = unarmed;
long timeGettingArmed;

/////////////////////////// Trigger ///////////////////////////////
//void trigger() {
//  systemState = alarm;

//////////////////////////// State Machine //////////////////////////
void loop() {
  check(); Serial.print ("switchPin = "); Serial.println (switchPin);
  Serial.print ("pir_SensorPin ="); Serial.println (pir_SensorPin);
  switch (systemState) {
    case armed:
      Serial.println ("armed");
      if (digitalRead (pir_SensorPin == HIGH)) {
        systemState = alarm;
      } else if (digitalRead (keypadPIN == LOW)) {
        systemState = unarmed;
      }
      break;
    case unarmed:
      if (digitalRead (pir_SensorPin == HIGH)) {
        Serial.println ("unarmed");
        timeGettingArmed = millis(); // Or just do a delay here.
        systemState = justActivated;
      }
      break;
    case justActivated:
      Serial.println ("juatActivated");
      if (timeGettingArmed + waitTime < millis()) {
        systemState = armed;
      }
      break;
    case alarm:
      Serial.println ("alarm");
      if (digitalRead (keypadPIN == LOW)) {
        systemState = unarmed;
      } else {
        beep();
      }
      break;
  }
}

//////////////////////////// Alarm //////////////////////////
void beep() {
  Serial.println("at beep");
  // (sms.SendSMS("**********", "*** Motion Detected in Studio! ***"));
  Serial.println ("MOTION detected: SMS Sent");
  for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
    digitalWrite (alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
    digitalWrite (alarm_OutPin, LOW); delay (500);
    digitalWrite (led_OutPin, HIGH); // delay (1000);
    Serial.println (alarm_count);
  }
  systemState = armed;
}

void check() {
  if (digitalRead (switchPin == HIGH)) { // manual test in lieu of keypad attached
    (keypadPIN = LOW); // unarmed
  }
  else {
    (keypadPIN = HIGH); // armed
  }
  Serial.print ("switchPin = "); Serial.println (switchPin);
  Serial.print ("keypadPIN = "); Serial.println (keypadPIN);
}

Serial output shows:
pir_SensorPin =1
switchPin = 1
keypadPIN = 1
switchPin = 1

Your code to read from the pins is incorrect. You write
if (digitalRead (pir_SensorPin == HIGH)) {

However, this compares pir_SensorPin == HIGH, (which is 2 == HIGH), producing a true or false that it then passes as the argument to digitalRead, which will try to interpret that as a pin number. Fix your parentheses:
if (digitalRead(pir_SensorPin) == HIGH)  {

(This problem occurs throughout your code.)
You also are writing an input pin in your setup, which is not necessarily wrong (it is one way of enabling or disabling the pullup resistor), but you should understand why you're doing it:
pinMode (pir_SensorPin, INPUT);   // Set pinMode.
...
digitalWrite (pir_SensorPin, LOW);

The effect of writing to an input pin enables or disables (disables in this case) the internal pullup resistor. In earlier versions of the Arduino API there was no INPUT_PULLUP mode, so writing to the input pin was common. I suppose there are still plenty of examples and tutorials that still tell you to do that.

Thanks to you both. I am in the process of implementing its changes and my parentheses issues.

Majenko, thanks for the useful explanation. I really do need to finish reading that whole data sheet and then the library source....

Still not able to get a functioning operation, as I expect. I have since grounded my two input pins, with no success. I am getting the following outputs:switchPin = 1
PIRtriggerCheck = 0
switchPin = 1
1
The PIRtriggerCheck doesn't seem to get triggered. Code follows:

Write the simplest possible program that sets up two pins as input pins and then, in a loop, reads them and prints out their values. Tie one to 5V and the other to ground, and ensure you're getting the right readouts. If it doesn't work, edit the question to include the simpler code that's not working. If it does work, gradually add bits to the program to bring it closer to the final version, testing after each small change.


text:
Life span of arduino
We are students of Pragati Engineering College -AP. We are currently working on Automatic Street Light  project selected in Smart India Hackathon 2017 under ministry of steel. For this project  We are using Arduino nano to control street lights in industries. Now we are requiring some general following  information about arduino nano.
What is the life span of Arduino nano?
We need a micro-controller with on analog input pin to read analog voltage and four digital pins for output. The program that we are dumping include  serial communication with Java UI in PC. The program occupies 6750 bytes, 318 bytes for global variables and 1730 bytes for local variables. We would like to know which arduino board is best suitable for our project?

A few important  questions: will it be a genuine Arduino nano or a chinese clone? Do you write to EEPROM or not?

It might be better to design your own board with a bare "Arduino" chip on it. An ATMega328 or just a basic ATTiny85.

Atmel chips (the ones used in the Arduino) have been used in all sorts of industrial appilications way before Arduino came along. Same for other micro controllers like the still popular 8051.
What you want to focus on might be the enclosure, seal it against the outside.
Rather than using a (chunky) pre-manufactured Arduino board, you'll have to pick the right chip for your application and design a board around it. http://www.atmel.com/products/microcontrollers/avr/

What is the life span of Arduino nano ?

Many years.
Flash memory can degrade with time and the program can become corrupted or lost - however:

Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

Wet electrolytic capacitors dry out over time. When resurrecting old hardware the first thing you do is replace all the electrolytic capacitors. Depending on how much you de-rate them they could last a few years, or tens of years, before they need replacing. If possible avoid them and use MLCC and tantalum instead since they never dry out.
The biggest problem of any kind of industrial installation is that of the environment. Corrosion from airborne contaminates (water, etc) will destroy the PCB (oxidise the copper of the tracks, etc) long before the components have worn out. Proper sealing, and even "potting" in extreme environments, is essential for longevity.
Another important thing to remember is to factor in a certain number of failures over the intended lifetime of the product. If you find you will be needing to replace portions of a unit on a semi-regular basis then make those portions easy to replace. For instance, it may be more cost effective to routinely replace a board after 5 years rather than have to replace the entire unit every 8 years because the board that has failed is impossible to replace (e.g., it's potted).
As others have mentioned you shouldn't be using an Arduino of any form in a product. Instead you will be designing (or paying someone to design) a dedicated PCB. During that design phase extra steps can be taken to make the board more rugged - such as wider tracks and thicker copper that will take longer to corrode; increased clearances that will take longer for corroded copper to bridge; components chosen to have a suitable MTBF, etc.
Many components have a "service life" or "lifetime" quoted. This is especially important for components such as electrolytic capacitors. For instance, the EEUFR1C471 from Panasonic (to pick one at random) is quoted as 6000 hours at 105°C. 105°C is the maximum temperature you can run it at, so the quoted service life is a minimum at worst case parameters. 6000 hours is, of course, just 250 days (about 8 months or so) - but of course that is worst case, and the minimum guaranteed time (they guarantee that it will run for at least 6000 hours at 105°C). Run it at a lower temperature and you get longer life out of it.

What is the life span of Arduino nano ?

Electronics doesn't really "die". Treated well, it should last for years. I have a RFID security system that I made in 2011 (six years ago, as I write this) and it is still working perfectly.

We would like to know which arduino board is best suitable for our project ?

These sorts of questions are hard to answer. What is "best"? Price? Size? Weight? Ease of use?

Best is tot use high-grade components though and check if the environment is fit. Voltage spikes can kill electronics instantly. Moist or corrosion are also worth taking into account Things as a too high/low temperature can also affect the lifetime. Also microcontrollers don't really have a "fail safe" you may want to put the lights in a warming/error state (flashing orange) if odd behaviour is detected.

What is the life span of Arduino nano ?

the answer is use dependent. Just like you don't know for sure what's the life span of a particular individual, it is hard to know the life span of a product in a particular application, as it depends on the environment, design, and operations of that application.

We would like to know which arduino board is best suitable for our project ?

hard to tell, and likely none. street lighting is exposed all sorts of elements, from high / low temperatures to moistures and lightening for example, and demands high reliability in all conditions, particularly in failure. Arduino wouldn't be great in that environment.
if you have to go down that path, develop the code in arduino and burn the hex into bare chips so you have the choice of the chip and other components going into your application.


text:
Design vehicle tracking device
I want to create an Arduino based vehicle tracking device which will be moved into a production board without Arduino later. Right now I have a few questions:

What GPS module should I use for a best result (little time to fix from a cold start and high accuracy locations)? It will be good if support GLONASS. I want to detect when the car is turning (using HMC5983). I've bought Ublox NEO-6M GPS module and tested it into the car, but it cannot find a location.
What MCU I should buy? I also want to communicate with OBD II port of vehicle over the CAN protocol (using MCP2551 + MCP2515). For now i choose ATMega328.
How to power all elements ?

PS: Data from the vehicle and the GPS locations will be send over GPRS with SIM800l module.
Cheers

This is not on-topic for a good Arduino question.  Generally we want to see a goal, then your attempt to meet that goal, showing parts, photos, code, etc.  Then a very specific question that is also in the title about something that is holding you back from completing the project.  We can't design a project for you.  I highly recommend you read the tour at https://arduino.stackexchange.com/Tour to get the most of this site.  I am voting to keep this open to give you an opportunity to either edit it completely based on what you see in the tour, or delete it yourself.  You are welcome here.

There are some SIMCOM modules with GPRS + GPS, for example: SIM968
In addition to GPS, it also supports GLONASS/Galileo/QZSS.
As for the MCU, you will need something more powerful than ATMega328, because 2KB RAM is not enough for multi-threading + GPS code + GSM/GPRS code + CAN + etc. Also it hasn't CAN peripheral. You will need MCU with ARM core. From Arduino line, Arduino Due looks suitable: has 96KB RAM, multiple HW serials, CAN. There is also compatible CAN library here. Also worth looking on STM32F103 (or STM32F407 with Cortex M4) which also can used be with Arduino IDE with some extra effort (STM32 MCUs usually more cost effective than Atmel counterparts, and have higher performance).


text:
(SOLVED) Fast HW check: (18 digital + 4 analog to I2C ) Arduino Mini Pro + MCP23017 or STM32?
Arduino Mini Pro+MCP23017 or  STM32
I want make device, which reads 17 digital buttons and 4 analog, process it somehow and send the result to I2C bus. Also there is a LED to be managed. I may want to attach some wireless too later, but I am not really sure, if I woud do it (which would need 5-6 mor digital pins). I need to update the firmware often, as it is under heavy developement just now. I should make the PCB as soon as possible, but programming can wait some time.
The PCB would have buttons and analogs on it (and MCP in the arduino case). Also lot of connectors, like I2C, programming interface and some power regulators, the LED (or maybe more of them, if there was few free pins, but it is not mandatory). The processor will be connected via wires for space reasons (and maintainability and the board may be redesined later), so only long row of soldering pads on PCB for it.
Main decision:
If I opt to Arduino, then MCP will be part of the PCB and connected to I2C bus, if I use STM32, no MPC will be present and buttons would go directly to output connector.
Making the HW is no problem for me, the logic inside is also easy (basically read all inputs, normalize analogs to some range, make some simple tests and if desired, send result over I2C. Reply to some simple I2C too.)
I have a lot of Arduino Mini Pro, but it is few legs short for the task, so I would use MCP23017 expander for 16 of that digital buttons.
I also got some these STM32
https://www.aliexpress.com/item/STM32F103C8T6-ARM-STM32-Minimum-System-Development-Board-Module-For-Arduino/32279776568.html but did not open the package yet. Anyway I want to learn to use them "sometimes soon".
Maybe it is just the kind of starter project, which I would like to do.
Now I am just not sure about the number of available pins on the STM32, on first look it have more pins, but each description I found yet states too much details about additional functions, but I got confused about the basics here. So my question is:
Can mentioned STM be easilly programed as Arduino, manage I2C communication, and still have comfortable 18+4 I/O pins free? And 23+4 I/O free?

Have you heard the word "Multiplex"?

like in http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/ with the mentioned  MCP23017 expander? Yes, I did. I am also aware about resistor dividers to read more buttons. But the question goes other way - can STM32 do it without such tricks? If so, I will start learning it today, if not, I will postpone it to next month or two.

http://playground.arduino.cc/Main/KeypadTutorial

Nice, but I am not going to use this device, and I want to be able read all combination of buttons. Also I would like to be able to use interrupts to detect change, which is not possible with scanning methods.

@gilhad Why it shouldn't be possible? You can set all columns to zero and enable pin change interrupts on all rows. And when the interrupt is detected, you can start scanning for a while (with pin change interrupts disabled). Or it can be used for waking up from the sleep mode.

Good idea. Thank you. But anyway my problem is if I can easily use STM32 and "brutal force it" with enough pins (which I would like to do), or if it is not possible this way, in which case I would use Arduino mini and some kinds of "tricks" (which is plan B).

Can mentioned STM be easilly programed as Arduino, manage I2C communication, and still have comfortable 18+4 I/O pins free? And 23+4 I/O free?

it can be programed as Arduino, manage I2C communication, and still have 18+4 I/O pins free or 23+4 I/O free.
it is only knowable to the person programming it whether it can be done easily or comfortably.

I am the person and I need to learn that. In "easily" I mean like in arduino with the usual digitalRead(pin) for pin in 2..13 and A0..A7 and analogRead(pin) for pin in A0..A7 (avoiding A4/A5 for I2C). Just link Wire library, set some callback function like void receiveEvent(int howMany) . Without going to disable reset, repurpose Xtal pins and so on to get more available pins or other black magic. I consider the whole task easy on Arduino Mini Pro with MCP23017.  So the question is like would it be on equal "easy" on STM32 ?

Putting aside the additional task of setting up too chains for STM32, yes, the tasks would be equally easy if you have the corresponding libraries.

if you don't have the corresponding libraries, the task is not difficult if you reasonably proficient in reading / understanding datasheet and coding to it.

I can for example basically write a set of code that runs across the arduino and pretty much any chips I want, by hooking in the appropriate libraries as middleware.

Thank you, so it is decided and I wil go with STM32. I will set the compile/upload chains anyway, and I just found Wire library for STM32, so everything should go reasonable well :)


text:
Gravity fan does not work when powered by 3.3V ESP8266
The gravity fan has 3 pins. I connected one pin to the ground, one pin to the digital pin numbered 2 on ESP8266. I uploaded this code but the fan doesn't run at all. The fan supposedly uses a 5V power supply but the ESP8266 only supplies 3.3V. Could this be the problem?
void setup() {
  pinMode(2, OUTPUT);
}

void loop() {
  digitalWrite(2, HIGH);
}

If the fan needs 5V power you need to give it 5V power. 3.3V logic is not 5V power.

Don't power stuff from I/O pins. An LED may work, but a fan will require too much power and also has a possibility to generate power (when turned by hand/wind) and may damage the pin.

The ESP can only supply 12 milliamperes of current. The fan most likely uses a whole lot more. You could for example uses a transistor to turn on the fan.


text:
LCD display and ultrasonic sensor not functioning
I am doing fish feeder project with level detection for the feeds but lcd display and ultrasonic sensor did not function.
#include <LiquidCrystal.h>
#define trigPin 12              // the trig pin to digital pin 12
#define echoPin 13              // the Echo pin to digital pin 13
#define L 8
#define M 9
#define H 10
// #define trigmotor 1 //closelid
int led = A1;           // LED indicator to digital pin A1
#include <Servo.h>
Servo MyServo;

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

const int thresholdH = 0;
const int thresholdM = 70;
const int thresholdL = 90;
// defines variables
long duration;
int distance;
float percentLV;

void setup()
{
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600); // Starts the serial communication
  pinMode(led,OUTPUT);
  digitalWrite(led,LOW);            //set the led off(initial condition)
  lcd.begin(16, 2);
}
void loop()
{

int degreesOfRotation = 8;
int servoPinNumber = 11;
float hoursBetweenMeals = 12;
float mealDelayTime = 0;

{
    MyServo.attach(11);
    MyServo.write(degreesOfRotation);
    mealDelayTime = hoursBetweenMeals * 1800000;
    delay(20);

    while(degreesOfRotation < 152) {
        MyServo.write(degreesOfRotation);
        delay(10);
        degreesOfRotation += 1;
    }
    while(degreesOfRotation > 8) {
        MyServo.write(degreesOfRotation);
        delay(10);
        degreesOfRotation -= 1;
    }
    delay(mealDelayTime);
}

{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = (duration * 0.034 / 2);
  float percentLV = (40 - ( distance - 16 )) * 100 / 40;

  if (percentLV > thresholdL && percentLV < 100) {

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("PLEASE REFILL!");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, HIGH);
    digitalWrite(M, LOW);
    digitalWrite(L, LOW);
    //digitalWrite(trigmotor, HIGH);
    //delay(3000);
    //digitalWrite(trigmotor, LOW);
    //delay(1000);
    digitalWrite (led, HIGH);      // Turn on the led indicator
    delay(20);
  } else if (percentLV <= thresholdL && percentLV > thresholdM) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("U May Refill Now");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, LOW);
    digitalWrite(M, HIGH);
    digitalWrite(L, LOW);
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, HIGH);      // Turn on the led indicator
    delay(20);
  } else if (percentLV <= thresholdM && percentLV > thresholdH) {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Take it easy");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    digitalWrite(H, LOW);
    digitalWrite(M, LOW);
    digitalWrite(L, HIGH);
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, LOW);      // Turn off the led indicator
    delay(20);

  } else {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("FULL!!");
    lcd.setCursor(0, 1);
    //lcd.print(distance);
    lcd.print(percentLV);
    lcd.print(" %");
    //digitalWrite(trigmotor, LOW);
    digitalWrite (led, LOW);      // Turn off the led indicator
    delay(20);

    Serial.print("PercentLV: ");
    Serial.print(percentLV);
    Serial.println("%");
  }
  delay(1000);

}

}

Hello and welcome. Could you please be more specific about the errors you get. "not function" is quite hard to debug for the readers of your question. You might also want to add details about your system, display, and sensor. Note that you can always edit your question to include these details (do not put them in the comments section).

it did not function at all...the lcd display did not turn on and same goes to the ultrasonic sensor

Can you post a wiring diagram and specify the hardwares you are using?

Do these components work individually? Try making a "test sketch" for both the components to verify that they work and that your code works.

i am using servo motor, lcd display and ultrasonic sensor @rvbarreto

Ok, but we have to know which motor and which sensor. We need to know the model. We also have to know which arduino board you are using and - this is very important - how you are wiring them. Without this information nobody will be able to help you.

servo motor MG-995, ultrasonic sensor HC-SR04, lcd display 16x2 and arduino uno r3

There doesn't appear to be anything wrong from a quick glance.  Have you got the right library for the LCD?
The chances are there is something wrong with your LCD.  So check your connections again.  Now create a new sketch that just prints hello world on the LCD, or better still use an example.  If that works, then the problem is an interaction between components.
So write a sketch that spins the servo back and forth while printing a message on the LCD.
Did that work, now add in the ultrasonic sensor and the code.
Now the other bits, and if that works, then you could look at what you have done differently, or just thank your lucky stars :)


text:
What if I detach AVR micro controller from the Arduino Board after uploading program?
What if I detach AVR microcontroller from the Arduino Board after uploading program? Does the microcontroller still have the program on it? Or the program will be deleted?
On the board where does Arduino store hex file?
I am very beginner in Embedded Programming. I am learning about microcontroller and Arduino. While learning about programming Arduino-Uno I got these question in my mind.

the microcontroller itself stores the program in flash, so you can remove the part and move it elsewhere and the program goes with it.

Just look at the documentation for the AVR part it describes where the application lives.

historically there have been boards (basic stamp, etc) that the program on the microcontroller was an interpreter for a bytecode that actually lived on another device on the board, eeprom or flash.  No reason to do this on an arduino, since you are learning examine the schematic and see what else you see on the board, where else could the program live?  (combined with reading datasheets for the parts you find)

Make sure to check this link (https://www.arduino.cc/en/main/standalone)

The AVR µC got a flash memory that can store the code loaded in. That mean you can load the code with the arduino board, detach the avr and put it on another circuit. If the µC is powered well, it will behave just like the arduino.
Don't forget to set the /reset pin to high, if you do, the µC will be stuck to the 1st line of code ;)


text:
Using a potentiometer to control number of lit pixels on an NeoPixel strip
I'm working on controlling an Adafruit NeoPixel strip with an Arduino and a potentiometer. Specifically, I'm trying to use the potentiometer to control how many pixels are lit up on the strip. As I turn the potentiometer "up" (i.e., increasing the value), the number of lit-up pixels increases.
However, if I try to turn the potentiometer the other way and decrease the number of lit-up pixels, then the strip will stay at whatever the last value was.
I have a method below that's called during the 'void loop()' method that read in the potentiometer data:
void readAndSendPotentiometerDataIfChanged(void) {
 //Read data from analog pin 2, and scale it
 int newPotentiometerValue = analogRead(A2) / 5.68;
  if (newPotentiometerValue != lastPotentiometerValue) {
      Serial.print("POT. value");
      Serial.print(newPotentiometerValue);
      lastPotentiometerValue = newPotentiometerValue;

      /* The value of "colorVal" is determined by a switch, and seems to be
         working properly */
      if (colorVal == "RED") {
        //If the value is 0, we want to clear the pixel values to white
        if (lastPotentiometerValue == 0) {
          clearPixels();
        } else {
          colorWipe(strip.Color(255, 0, 0)); // Red
        }
      } else if (colorVal == "BLUE") {
        if (lastPotentiometerValue == 0) {
          clearPixels();
        } else {
          colorWipe(strip.Color(0, 0, 255)); // Blue
        }
      }
   }
}

The method below will clear out all 180 pixels on my strip to no color (clear).
void clearPixels() {
   uint16_t clearColor = (127, 127, 127);
   strip.setPixelColor(180, clearColor);
   strip.show();
}

Here's where the pixels on the strip get set...I'm sure the problem is in the for loop below, but I haven't been able to come up with a better way to set the pixels on the strip and then turn them on:
void colorWipe(uint32_t c) {

  /* Use the value of 'lastPotentiometerValue' to determine how many pixels
   on the strip should be lit up */
  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }
   strip.show();
}

Anyone have a pointer to how I could refactor my code so that the potentiometer works in both directions, and will light up or turn off the pixels on the strip as appropriate? Thank you!
EDIT Based on Ignacio's answer, I changed my colorWipe method to this:
void colorWipe(uint32_t c) {

  for (uint16_t i = lastPotentiometerValue; lastPotentiometerValue<180; i++){
      uint16_t clearColor = (127, 127, 127);
      strip.setPixelColor(i, clearColor);
  }

  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }

   strip.show();
}

However, now no strips are lit up.
EDIT 2
The condition was wrong; below is the code that works:
void colorWipe(uint32_t c) {

  for(uint16_t i = lastPotentiometerValue; i<180; i++){
      uint16_t clearColor = (0, 0, 0);
      strip.setPixelColor(i, clearColor);
  }

  for(uint16_t i=0; i<lastPotentiometerValue; i++) {
    strip.setPixelColor(i, c);
    delay(0.5);
  }

   strip.show();
}

You forgot to clear every other pixel in colorWipe(). Pixels that aren't sent a color retain their previous color.

That makes sense. So, something like (180-lastPotentiometerValue) would determine the pixels I need to clear, right?

No, everything from lastPotentiometerValue through 180.

That also makes sense; though I'm not sure how to keep that from resetting all the pixels (I made an edit to the question).

You goofed the condition.

How so? Apologies; not seeing what you're seeing :/

You need to compare i.


text:
Press on pressure sensor once, turn on LED for 6 seconds
I am working on a project where I would like to press on a pressure sensor (0-1024) once and turn on the LED and turn off by itself after 6 seconds. I am quite new to arduino and I can't seem to understand how to code this with using a pressure sensor as a switch rather than an actual switch. Any ideas?

When it is allowed that the Arduino does nothing during the delay, you can use the delay() function. Using millis() is a lot better, but that requires a specific way to use it. The Blink Without Delay ( https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay ) is a start to learn how to use millis(). Is the pressure sensor a FSR ? Is it a school project ? Can you show your sketch ?

Sensors which give a range of outputs need to have their outputs processed using a technique called hysteresis.  That is, normally, the turn on threshold is higher then the turn off threshold.
For example, the thermostat in your home uses hysteresis when controlling your HVAC system.  Otherwise your thermostat would constantly be turning on and off your HVAC system likely causing an early failure.
Here is a stackexchange Arduino question about hysteresis.

If you're having a problem implementing the system in software, there is a hardware approach to do it. The phenomenon is called monostable multivibrator. Monostable mode retains its output for a certain time interval before coming back to previous state. You can use a simple RC circuit configuration to implement this functionality along with Arduino setup. Just interface FSR in voltage divider format, read the voltage and switch another GPIO interfaced with RC circuit configuration.


text:
How to pass input from a Midi controller to a function?
I am trying to pass the input[], data1(pitch) from a Midi controller to the waitForButton function. When a key is pressed it sends data1(pitch) into the array input[], and when the key is up the array value goes to zero. But the input isn't being passed to the function as I am pressing the keys on the Midi controller. What am I missing?
void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1==48) { //C3
    Status[0][0]=1;
    noteOn(0,data1,100);
    input[0]=data1;
  }
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity) {
  data1 = MIDI.getData1();
  if (data1==48) { //C3
    Status[0][0]=0;
    noteOff(0,data1,100);
    input[0]=0;
  }
}

void readsequnce() {
  bool mademistake = false;
  int key;
  for (int index = 0; index < largestindex & mademistake == false; index++) {
    key = waitForButton(5000);
    if(key ==-1 || key != note[index]) {
      mademistake = true;
      state = 2;
    }
  }
}

int waitForButton(int laps) {
  int keyPressed= -1;
  int check;
  boolean keyBackUp = false;
  currentMillis = millis();
  // The number of ms since the program started running
  previousMillis = currentMillis;
  // Records the point when we start spinning the loop.
  // Keep spinning the loop until "delay" seconds have passed.
  while (currentMillis - previousMillis < laps & keyBackUp == false) {
    lcd.setCursor(16, 2);
    lcd.print(String(keyPressed));
    // Read the button and record when it has been pushed down.
    for (int i = 0; i < 25 & keyBackUp == false; i++) {
      if (input[i] != 0) {
        keyPressed = input[i];
        // Show the LED pushed.
        noteOn(0, keyPressed, 100);
        //  digitalWrite(leds[pin], HIGH);
        // It is possible the button is still being pushed.
        // This loop spins until the button is let up.
        while (currentMillis - previousMillis < laps & keyBackUp == false) {
          check = input[i];
          if (check == 0) {
            keyBackUp = true;
          }
          currentMillis = millis();
        }
        // Turn the LED pushed off.
        noteOff(0, keyPressed, 0);
        // digitalWrite(leds[pin], LOW);
        // See if they took to long.
        if (currentMillis - previousMillis > laps) {
          keyPressed = -1;
          // They took to long to let the button up so they lose.
        }
      }
    }
    currentMillis = millis();
  }
  return keyPressed;
}

the change of the array is shown in the  MyHandleNoteOff and  MyHandleNoteOn functions.

You don't need to call getData1() because the MyHandle function already get this in their parameters. You are probably not using volatile.

so i should use pitch instead of data1 ?

@CL. making that change had no effect.i think the while loop is blocking.dose it look like the while is the issue?


text:
ATtiny85 LM75 I2C
I would like to read temperature from a LM75 using the ATtiny85 running a core by SpenceKonde and utilizing the TinyWireM library.
My Logic Analyzer does not pick up any I2C communication, when I connect it to an Arduino Nano, it works fine. On the Nano, there is no need for TinyWireM so that's a big difference.
Therefore I conclude that the ATtiny85 is not speaking the right I2C slang to the device.
I also use SoftwareSerial and this works fine. It is visible on the Logic Analyzer.

The LM75 library is not made for ATtiny or TinyWireM, I replace the Wire references in-place by TinyWireM reference.
Should it be possible to 'just' replace Wire by TineWireM in the library and could I expect some meaningful data this way?
[updated code]
#include <Arduino.h>
#include <TinyWireM.h>
#include <LM75.h>
#include <SoftwareSerial.h>

#define SOFTWARE_SERIAL_TX_PIN 3
#define SOFTWARE_SERIAL_RX_PIN -1

LM75 sensor;
SoftwareSerial mySerial(SOFTWARE_SERIAL_RX_PIN, SOFTWARE_SERIAL_TX_PIN);

void setup() {
  TinyWireM.begin();
  mySerial.begin(2400);
  mySerial.print("Starting..");
}

void loop() {
delay(1000);
mySerial.println("SO");
mySerial.println(sensor.temp());
delay(1000);
}

Could you post your code?

I have added te code I use to test

Looks like the setup() is missing a call to TinyWireM.begin(). Also do not forget pullup resistors.

The TinyWireM.begin() is part of the library and I have the pull-ups, this setup works on an Arduino Nano

i2c is fairly easy to implement, either hardware or software. so you may find it beneficial to just write your own.

@Thijs The setup cannot work on Nano as it does not support USI which is the ATtiny hardware module.

Use LM35 which is analog.

The current ATtiny core includes a Wire library for the USI hardware used in the Tinys. This way you don't need to modify the LM75 library which is error prone.

Thanks, that piece of the code went missing when I edited the question (6 months ago). Problem remains.

Might help if you update the code to what you're actually using. Keep in mind that you won't see anything in the resolution you've chosen in the logic analyzer as I2C is about 50 times faster than the serial.

I updated the six months old question you answered with the code I might have used back then. But please tell me more about the speed of I2C.

Hi and welcome to the Arduino SE community. Please expand on your answer. You have identified some issues but please update your answer with how to resolve these issues. For example you could demonstrate the solution with some snippets of code and an explaination of how it fixes the problems the OP is having.

This is an old post I know but hopefully this information is helpful to someone. I modified the lm75 library by replacing all instances of Wire with TinyWire and as above no go, but turns out a 10k pull up on SCL / SDA is a necessity for the attiny 85. For whatever reason i2c works fine on an arduino UNO without pull ups but not on an attiny 85. So in short, add pull up resistors and it works. Bonus potato grade picture of attiny, LM75 and display module showing temperature.

hi Tom, thanks for the reply and the great picture :D could you please share information about your code? what library and core you used for example. I’ll try it out but I think I had the pullups back then..

I pretty much just used the lm75 and TinyWireM library, made a copy of the lm75 library, renamed it to lm75tiny and replaced any instances of Wire with TinyWireM. Ended up with this:
#include <TinyWireM.h>
#include <lm75tiny.h>
TempI2C_LM75 termo = TempI2C_LM75(0x49,TempI2C_LM75::nine_bits);
Then read temperature like so:
int temp = termo.getTemp();
Only other gotcha is the address of the lm75 needs to be confirmed and updated for whatever sensor you are using. I think the default is 0x48 but my sensor was 0x49.

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


text:
How to change colors and theme settings in 'Windows Store app' version of Arduino IDE?
In the standard Windows (Win32) version of the Arduino IDE, theme settings like syntax coloring can be modified in C:\Program Files (x86)\Arduino\lib\theme\theme.txt.
For the Windows Store app version of the IDE the theme files are stored in protected app storage space.
Is there a simple/safe way to change theme settings for the Windows Store app version of the IDE without messing up security settings and inadvertently lowering Windows security?
(It would be easier and better if theme settings could be moved to the ArduinoData user folder where preferences.txt is stored.)

Don't use the Windows App Store version?

I assume not using the Windows Store version is not an option (because that's the easiest answer).  An alternative that might work (if you have admin access) is to use Junction.exe to create a symbolic link between a writeable directory and where the themes are stored. But changing the perms on that directory is going to be easier.

I think rrz0's answer skipped the part of the question:
"For the Windows Store app version of the IDE the theme files are stored in protected app storage space."
The only way is to take control of the windows app folder but I believe this is risky and M$ suggests that this can brick your pc (take that with a grain of salt).
There is an offline windows installer and zip link on the downloads page which I used to replace the windows store version. I see no advantage to the store version.

Working from what Ignacio Soler Garcia wrote (which didn't work for me), I tried around and came up with a solution for my case (I downloaded the OneDarkArduino Theme from GitHub):

Unpack the theme if it came in a ZIP file
copy the folder called "theme" (there should be a bunch of .txt and .svg files in there)
paste it into the folder where all your projects are (usually something like C:\User\Documents\Arduino) - it needs to be named "theme"
(re)start the Arduino IDE and now it should start with the new theme already loaded

I can confirm that changing ownership/security on the WindowsApps folder half-bricked my machine... it still ran classic windows but every single store App wouldn't run and the store itself stopped working... and I couldn't reset the security back again - 4 hours later and a complete restore with Microsoft's recovery download and a 16GB USB boot load , I'm older and wiser.

There is a way, but not necessarily simple. You basically need to replace the current theme files with the new ones.

Rename {Arduino IDE installation folder}/lib/theme to {Arduino IDE installation folder}/lib/theme.bak
Download https://github.com/jeffThompson/DarkArduinoTheme/archive/master.zip
Copy the theme folder from the downloaded file to {Arduino IDE installation folder}/lib
Restart the Arduino IDE if it's running.

I found the solution, based on a new functionality for themes that I wasn't aware of.
You need to create a themes folder in the folder where your projects are (the one that appears in the preferences section) and put inside it the theme in a zip file. After restarting it will appear as a new theme in the combobox themes.


text:
RadioHead and DallasTemperature error
The RadioHead library only runs on a very old core for the ATtiny85.
It sends data but I would like to send something useful. The problem is I cannot read any sensors using this core. And on any other core the RadioHead library fails.
RadioHead library
ATtiny core
An old post in the Arduino forum, probably the same issue.
I would like to know what is in the DallasTemperature that conflicts with RadioHead making the code to hang.
The problem appears when I add DallasTemperature sensors(&oneWire); to the code.
// RadioHead ASK
#include <RH_ASK.h>

// DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS PB0
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// Sleep
#include <avr/sleep.h>
#include <avr/wdt.h>

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// Absolute reference PB to overcome inter-IDE issues
#define T_PIN PB1 // transmission
#define L_PIN PB3 // optional LED pin
#define BAUD 2000

// Baud rate, receiver, transmitter
RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

// the Tickle structure, what a name, ugh
struct tickle {
  uint16_t id;
  uint16_t value1;
  uint16_t value2;
};

// Watchdog
volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

// Sleep
void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

// Setup for Watchdog
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

// With set_watchdog at 8 (4 sec.) we cycle from 0 to 14
// This timer is not precise
void minute_sleep(int ms) {
  for (int c = 0; c < ms; c++) {
    for (int i = 0; i < 15; i++) {
      system_sleep();
    }
  }
}

void setup() {
  // Debugging, if this takes less than a second, check fuses (core)
  if (!driver.init()){
    pinMode(L_PIN, OUTPUT);
    digitalWrite(L_PIN, HIGH);
    delay(500);
    digitalWrite(L_PIN, LOW);
    delay(500);
  }
  setup_watchdog(8);
  sensors.begin();
}

void loop()
{
  if (f_wdt==1) {
    f_wdt=0;
    struct tickle package; // make a Tickle package

    package.id = 38; // hard-coded device ID
    package.value1 = analogRead(PB0); // any positive int up to 2^16
    package.value2 = analogRead(PB2); // any positive int up to 2^16

    // sending data
    driver.send((uint8_t *)&package, sizeof(package));
    driver.waitPacketSent(); // wait for it ~Barney
    minute_sleep(10); // tested: 10 was 10:30, I like
  }
}

I have experienced many issues when using RadioHead library on ATTiny85 together with the Arduino IDE. Your issue is not the Dallas temp sensor.
The problem lies in that RadioHead uses timer 0 on the ATTiny and changes the prescaler on the timer to match the baudrate you have requested for your tranciever. The change of prescaler changes the way Arduino IDE functions like delay()works since those also use timer 0. I believe your Dallas library depends on delay() to synchronize the signals on the 1-bus so there you have a conflict between the two libraries.
I solved this by rewriting the RadioHead RHASK files to allow for ATTiny85 timer 1 to be used instead. Here's my code. Although I use TinyHead instead of RadioHead, the change will be the same as TinyHead is a RadioHead clone.
The only change I made to RH_ASK.h is the code to define whether to use TIMER1 or not.
// Flag to indicate whether to use timer1 in attiny85.
#define RH_ASK_ATTINY_USE_TIMER1

The below changes goes into RH_ASK.cpp
First change. Update pre-scaler code and add the pre-scalers used by timer 1:
// Put these prescaler structs in PROGMEM, not on the stack
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO) || (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
#if defined(RH_ASK_ARDUINO_USE_TIMER2)
// Timer 2 has different prescalers
PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 32, 64, 128, 256, 3333};
#else
  #if defined(RH_ASK_ATTINY_USE_TIMER1)
   PROGMEM static const uint16_t prescalers[] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16834, 3333};
  #else
   PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 64, 256, 1024, 3333};
  #endif
#endif

Second change. This code sets up the timer 1 and goes before the existing code for ATTINY timer0 in function RH_ASK::timerSetup(). please note the "... existing code" part. The existing code for setting up timer 0 goes between the #else and the #endif
#if defined(RH_ASK_ATTINY_USE_TIMER1)
#warning RH_ASK_ATTINY_USE_TIMER1 set.
   // figure out prescaler value and counter match value
   // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
   // At 1MHz clock, get 1/8 of the expected baud rate
   prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);
   if (!prescaler)
       return; // fault

   TCCR1 = 0; // Stop the timer
   TCNT1 = 0; // Zero the timer
   GTCCR = _BV(PSR1);  // Reset the prescaler

   // Number of ticks to count before firing interrupt
   OCR1A = uint8_t(nticks);

   TCCR1 = _BV(CTC1); // Turn on CTC mode / Output Compare pins disconnected

   // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02
   TCCR1 |= prescaler; // set CS00, CS01, CS02 (other bits not needed)

   // Set mask to fire interrupt when OCIE1A bit is set in TMSK
  #ifdef TIMSK0
   // ATtiny84
   TIMSK1 |= _BV(OCIE1A);
  #else
   // ATtiny85
   TIMSK |= _BV(OCIE1A);
  #endif
#else
#warning RH_ASK_ATTINY_USE_TIMER1 not set.
   // use timer 0 (default)
   // figure out prescaler value and counter match value
   // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
   // At 1MHz clock, get 1/8 of the expected baud rate
   prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);

... existing code

   // ATtiny85
   TIMSK |= _BV(OCIE0A);
  #endif
#endif

Third change goes where the vectors are set up. Note the added #if defined for TIMER1 and the corresponding vector. Note also that the vector for timer0 is now called TIM0_COMPA_vect in later RadioHead/TinyHead but the names TIMx and TIMERx are interchangeable.
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO)
#if defined(RH_PLATFORM_ATTINY)
 #if defined(RH_ASK_ATTINY_USE_TIMER1)
  #define RH_ASK_TIMER_VECTOR TIMER1_COMPA_vect
 #else
  #define RH_ASK_TIMER_VECTOR TIMER0_COMPA_vect
 #endif
#else // Assume Arduino Uno (328p or similar)

Mind you that I have had other issues using the DallasTempSensor library. I'm not sure whether the issue is a low quality crystal in my ATTiny or not, but I get garbage readings from my sensor. The same code works flawlessly on my Arduino Nano, so I'm currently investigating whether my ATTiny is too far off in its timings to work properly with that library. I'm also going to try the OneWire protocol to see whether that one works better. However, the above code change resolved my issues with Arduino IDE and RadioHead/TinyHead.

This sounds great, I thought that the ATtiny85 only had a single timer.. the TinyHead is my light copy of RadioHead and I will test your code in a new version of this library as soon as possible!

Hi there, it has been a long time but I'm looking into this now. I cannot find any suitable place for you code to go. The #else suggests that more code will follow so it does not belong in timerSetup() in RK_ASK.cpp?

@Thjis, I have updated the code changes above. I hope it helps. The changes goes in RH_ASK.cpp with only the actual #define in RH_ASK.h.
BTW, I see the link to your GitHub was broken so I have updated the link to point to enisocha.

Thank you! I have moved to GitLab: https://gitlab.com/thijsvanulden/TinyHead and applied for a listing on the platformio library index. I will test your code, thank you for your input!! Also, my Dallas sensor works fine for me, I use DallasTemperature from the platformio library index.

I made the changes and TinyHead works fine with the Timer1, thank you for that. But the the Dallas library does break the radio transmission somehow. As soon as I call sensors.requestTemperatures() I can't send any radio transmission anymore.

I've been successfully using the OneWire library https://github.com/PaulStoffregen/OneWire. The upside is that it works for me but the downside is that you need to know what commands to send over the 1-wire and how to interpret the byte responses. I gave up on the DallasTempSensor library because I got unreliable readings on the ATTiny.


text:
ESP8266 ESP-12 Connection
I am connected with my ESP-12 through a programmer and all the AT functions work correctly. However I do not get a connection when connecting to the ESP8266 module.
I have done the following:
Set the mode both: AT+CWMODE=3
Connect to an Access Point: AT+CWJAP="<name>","<password>" (Responds with WIFI Connected and WIFI Got IP)
Set the Access Point: AT+CWSAP = "<other_name>","<password>",<channel>,<password_security>
So at this time it should be connected to my local network and I can connect to it through wifi on my laptop. However when I connect to it, it says 'Connected, No Internet' (The network the esp8266 module is connected to, has internet).
When I troubleshoot problems it says DNS is not responding.
Does anyone have a clue what to do next? Or what I might do wrong?

ESP8266 isn't a router. It doesn't route your laptop traffic to the AP with the internet.

Also this problem has nothing to do with Arduino.

It is an Arduino like module which can be set with Arduino and is able to be set as Access Point so it should be able to connect and have internet,..

make sure to set your AP to the same channel as the STA.

@dandavis Thanx for the good tip! :) But I indeed made sure the channel was the same.

You mention that in many different circumstances that you are somehow "connected" to something. But I have no idea what you mean. (Perhaps you tied them together with a piece of string? Or wired together two terminals but left both devices turned off?) You need to say not that you were "connected" but that you performed a specific test and got a specific response, e.g., "From my laptop, with IP address 1.2.3.4, I pinged 1.2.3.5 and got back a response." Also, giving us a link to the documentation from which you're working would be handy.

You can make the ESP8266 behave as a router, see Google for details.  By default it won't do this.
You need to create two separate WIFI networks and then tell the ESP to 'route' traffic between them.
Your ESP needs to form one network (STA mode?).  Your laptop needs to be on one network with the ESP.  The laptop needs to be configured to use the ESP as the gateway and unless your ESP has a DHCP server the laptop needs a static address.
Your ESP also needs to be a client to you router's network, and needs to take an address from the Router's DHCP server.


text:
MATLAB and Arduino communication
I have to send from MATLAB to Arduino a char line 'S' to start the Arduino program and send back values from a sensor.
This is my MATLAB code

clear;
delete(instrfind);
s = serial('/dev/cu.usbmodem1411','BaudRate',9600, 'Terminator','CR/LF');
fopen(s);
fprintf(s,'%s\n','S');

t = 0;
valor=zeros(1,100);
tiempo=zeros(1,100);
fid=fopen('resultats.txt','w');
for i=1:100
    a = fscanf(s,'%d');
    wd = 0.0189*a - 14.499;
    valor(i)=wd;
    tiempo(i)=t;
    fprintf(fid,'%3d %6d\n', wd,t);
    t = t+200;
end
plot(tiempo,valor);
fclose(fid);
fclose(s);

and my Arduino code is this
int outValue = 0;
unsigned long time;
void setup() {
  Serial.begin(9600);
  while (Serial.available() <= 0 || Serial.read() != 'S') {
    Serial.println("Send 'S' to start");
    delay(200); }
  Serial.println("Starting measurement");
}
void loop() {
  outValue = analogRead(A0);
  Serial.println(outValue);
  delay(200);
}

the problem is that when I use the MATLAB code it send an 'S' and it makes Arduino start sending values back, but Arduino does not do that and just sending the while loop again and again.
Is the problem in the MATLAB code when it send the char 'S'?

Could you try delaying for a couple of seconds between fopen(s); and fprintf(s,'%s\n','S');?

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


text:
SPI Problem with K-Thermocouple and Potentiometer?
I have a setup where the Arduino reads input from the k-thermocouple and uses that info to regultate the an output voltage through a potentiometer. I know the potentiometer is not faulty because able to read the output from the wiper when I run the program but for some reason, k-thermocouple is stuck at 0 Celsius. I know that the k-thermocouple is not faulty either because it works accordingly when I run a program specifically by itself.
Does anybody know why there is a problem with how the k-thermocouple is operating in junction with the potentiometer? Here is a declarations of my program.
#include <SPI.h>

// K-couple dependent DigiPot Regulator

#include "SPI.h"
#include "max6675.h"

byte address = 0x10;
int CLK = 13;
int CS = 10;
int SDI = 11;
const int ktcSO = 12;
int ktcCS = 9;
int ktcCLK = 13;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

int digitalPotWrite(int value) //Everything that happens when the DigiPot is
called
{
  digitalWrite(CS, LOW); // Chip Select is ACTIVE LOW (so now it's selected)
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

void setup()
{
  SPI.begin();
  pinMode (CLK, OUTPUT);
  pinMode (CS, OUTPUT);
  pinMode (SDI, OUTPUT);
  Serial.begin(9600);
  // give the MAX a little time to settle
  delay(500);
}

void loop()
{
  if (ktc.readFahrenheit() < 60)  // While it's still in Safe Zone
  {
    digitalPotWrite(255);
    // Show the current temp in C and F
    Serial.print("Deg C = ");
    Serial.print(ktc.readCelsius());
    Serial.print("\t Deg F = ");
    Serial.print(ktc.readFahrenheit());
    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
    Serial.print("\t V = ");
    Serial.println(voltage);
    int clockValue = analogRead(A1);
    Serial.print("\t Clock = ");
    Serial.println(clockValue);
  }
        if (ktc.readFahrenheit() < 65) // While in Caution Zone
        digitalPotWrite(51);
        else if (ktc.readFahrenheit() < 70)
        digitalPotWrite(102);
        else if (ktc.readFahrenheit() < 75)
        digitalPotWrite(153);
        else if (ktc.readFahrenheit() < 78)
        digitalPotWrite(184);
        else if (ktc.readFahrenheit() < 80) //Getting into Danger Zone
        digitalPotWrite(204);
        else if (ktc.readFahrenheit() < 81)
        digitalPotWrite(214);
        else if (ktc.readFahrenheit() < 82)
        digitalPotWrite(224);
        else if (ktc.readFahrenheit() < 83)
        digitalPotWrite(235);
        else if (ktc.readFahrenheit() < 84)
        digitalPotWrite(245);
        else (ktc.readFahrenheit() < 85); //Complete Shutoff
        digitalPotWrite(255);
    {
     Serial.print("Deg C = ");
     Serial.print(ktc.readCelsius());
     Serial.print("\t Deg F = ");
     Serial.print(ktc.readFahrenheit());
     int sensorValue = analogRead(A0);
     float voltage = sensorValue * (5.0 / 1023.0);
     Serial.print("\t V = ");
     Serial.println(voltage);
     int clockValue = analogRead(A1);
     Serial.print("\t Clock = ");
     Serial.println(clockValue);
    }
}

Also, the code I used to test the K-Thermocouple is one that can be found on the internet (with just a little bit of adjustments)...
// Sample Arduino MAX6675 Arduino Sketch

#include "max6675.h"

int ktcSO = 12;
int ktcCS = 9;
int ktcCLK = 13;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

void setup() {
  Serial.begin(9600);
  // give the MAX a little time to settle
  delay(500);
}

void loop() {
  // basic readout test

   Serial.print("Deg C = ");
   Serial.print(ktc.readCelsius());
   Serial.print("\t Deg F = ");
   Serial.println(ktc.readFahrenheit());
   int clockValue = analogRead(A1);
    Serial.print("\t Clock = ");
    Serial.println(clockValue);

   delay(500);
}

Please edit your question to include a circuit diagram.  Which lines do you have pullups on? What do you have connected to MISO, dig. pin 12?  Do you have an oscilloscope to check the clock signal during temperature reads, or to check data bits at MISO during reads?

Yes, I have MISO connected to pin 12. When I run a program to test the K-Thermocouple itself, I do get a square wave clock signal on the oscilloscope but then when I run the program above, the clock signal is indiscernible. It looks like a complete noise.

What's attached to A1?  Why is clockValue reading differently in the two sketches?

I think that may be the cause of my problem. When I had it hooked up to an oscilloscope, I was getting a pulse wave for the first one but the second one was complete static and indiscernible. This is what leads me to believe that the issue is rooted from the CLK signal of SPI with both the K-Thermocouple and the DigiPot in conjunction.

The wiring diagram, if accurate, shows a couple of problems.
First, A0 has nothing attached to it, so sensorValue may read in as zero or some small random number.
Second, attaching the digital pot's analog output pin 6, P1W, to the Uno's digital input pin 12 is pointless.  Instead connect P1W to whatever it is supposed to control.  If you want to handle data from the MCP42X1, connect its pin 13, SDO, to an Uno input.
However, neither of those problems appears to be related to misreading the MAX6675 temperature.  I don't know of a good approach to solving that problem, but if I were working with the circuit, would remove the wire between P1W and the Uno's digital pin 12, and would use 12 as the input from the MAX6675; that is, would wire it to d12 instead of d8, and instead of int ktcSO = 8 would say const int ktcSO = 12.  Also, I'd probably replace the bit of code
  }
  else
  {
    while (ktc.readFahrenheit() < 85)
      {

with just a closing }.  In the Arduino paradigm, loop() runs repeatedly, and the if–else sequence adequately guards each of the digitalPotWrite() calls.
Note, the digitalPotWrite() function should be defined or declared before any calls to it appear.  Instead of placing that function at the end, put it before  loop() or before setup().

My mistake on the A0. I originally had it there and switched it to D12 sometime during my troubleshooting process.
One question tho... I'm assuming your're saying I should replace the highlighted portion with
"}  loop()"
but wouldn't the program get stuck in loop the moment it enters it?

Looks like I read it wrong. No additional loop.

jwpat7 So I've applied all the changes that you suggested and the MAX6675 is still not registering any input. Side note: I have P1W connected to A0 so that I can monitor my output and also don't pay any mind to Vdd and Vss. I have them correctly connected in my circuit.

I added a few lines of code to try and show the clock signals (D13 <--> pin 2) of the MAX6675 when tested by itself and the whole circuit. There is some form of signal output every loop for the MAX6675 test itself but there is no signal when tested for the whole circuit.

The reason for replacing those five lines of code is that (1) your program will get stuck in the while (ktc.readFahrenheit() < 85) loop if readFahrenheit() isn't working or if you aren't changing the temperature at the sensor.  If it's stuck in that while loop, it won't produce any output.  And (2), decoupling the rest of loop() from its first 15 lines simplifies figuring out what it is doing.

I don't get exactly what you mean by  “some form of signal output every loop for the MAX6675 test itself but there is no signal when tested for the whole circuit” – in particular, it isn't clear to me whether your  “MAX6675 test itself” just loads and runs a specialized MAX6675-testing sketch, leaving the wiring as is, or whether you change just the hardware, or if you change both.  Given my lack of understanding of that, I don't know if you should be looking for a hardware issue or software.  Does all the hardware work ok if you run specialized test sketches, leaving the wiring as is?

Yes, that's exactly what is it. I ran a specialized testing sketch for the MAX6675 alone with the wiring as is and it works just fine. That's what the first side of the result picture shows. The right side is the output of the whole circuit. I added a few lines of code to print out the clock signal (value) during each loop since I don't have an oscilloscope at hand at the moment and I don't know how else to display the Serial CLK through my Arduino IDE.

I didn't see those outputs when I was editing my answer.  Anyhow, if you add the exact code for the left side output, and the exact code for the right side output to the question, I'll look at the code again.  Can you update the circuit diagram to match what you have, with A0 connection fixed?

I updated the circuit diagram and included the changes suggested in the main code as well as including the code used to test the K-Thermocouple.