text:
How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?
I have been trying to generate a PWM wave of 38 Khz (13 microsec= ON period , 13 microsec= OFF period).  Currently I am using Timer 0 to generate the PWM wave , however i am confused as to how to prescale the 16Mhz input clock frequency so that i can get 38 Khz from it .
The code is as follows -
#include<avr/io.h>
#include<util/delay.h>

uint8_t  dutycycle;
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        DDRG |= (1<<PG5);

        // Clear o/p on Match and Fast PWM Mode
        TCCR0A |=(1<<COM0A1) | (1<<WGM01) | (1<<WGM00) | (1<<COM0B1);// COM0A1/0b1 are the ouput ports , and WGM01 and WGM02 are used for fast PWM mode
        TCCR0B |=(1<<WGM02) | (1<<CS01);//WGM02 is used to set the fast pwm mode with max value stored in OCRA. CS01 is used to prescale the clock frequency to 16Mhz % 8 .
        OCR0A = 52;

}
void dutycycleA(uint8_t dutycycle)
{
    OCR0B = (dutycycle * 52)/100 ;
}
int main()
{
        pwm_init();

        while(1)
        {
            dutycycle=50;
            dutycycleA(dutycycle);
            _delay_ms(1000);
        }
}

So , the code is supposed to keep checking the value of OCR0B with the timer value and if it is less than that , then the output is logic HIGH , and if it is same as the timer value , then it'll be logic LOW . the duty cycle is given as 50 so that a pulse waveform of 50% duty cycle is reached .
However I am unable to obtain 38Khz output .
Please help me figure out where I have gone wrong and also suggest corrections to my approach , if wrong .
Thank you .
PS - I am using Eclipse Neon platform.

It appears that you didn't set any Clock Select bits.  Per datasheet,

clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped.

That could account for getting no output at all, if that's what's happening.  [I had overlooked (1<<CS01) in your TCCR0B setup.]
You have the COM0A1 and COM0B1 bits set, and you apparently assume COM0A0 and COM0B0 are clear. (Note that in the code below, I say TCCR1A = ... and  TCCR1B = ... instead of using |=, because |= is not reasonable to use for initial setup).  In the #7 fast PWM mode that you selected via WGM bits, this would lead to OC0A and OC0B clearing on their respective Compare Matches and setting at BOTTOM, which looks more or less ok for the OC0B pin, if you have OCR0B set to about half of OCR0A.  If the OC0A pin clears, however, it probably gets set again a cycle later, if I understand correctly.  (However, I'd want to actually test the code, with oscilloscope connected, to say for sure.)
Note that the OCR0A count of 52 and prescaler of 8 will set up a counting frequency of 1600000/(52+1)/8 Hz, ie about 37735.85 Hz, while a count of 51 would give 38461.54 Hz.  If accuracy matters, you can use simpler and more accurate code like the following.  It uses a prescale of 1 and count of 209, to generate a toggle frequency of 1600000/(219+1) Hz, ie about 76190.48 Hz, and a square wave frequency of about 38095.24 Hz.   Note, this code is written for timer 1; it should be straightforward to adapt to timer 0, because 209 is less than 255, the upper limit of TCNT0.
// Generate a constant frequency on PB1, using Fast PWM - jw May 2017
enum { OC1Apin = 9 };    // Arduino digital pin #9 = OC1A = PB1

void setup() {  // Set up timer 1
  noInterrupts();               // Turn off interrupts during setting
  TIMSK1 = 0;                   // Turn off timer 1 interrupts
  // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
  TCNT1 = 0;                    // Zero the counter
  TCCR1A = 1<<WGM11 | 1<<WGM10  // for Fast Pwm with TOP from OCR1A
    | 1<<COM1A0;                // To toggle OC1A PB1 D9 on Compare Match
  TCCR1B = 1<<WGM13 | 1<<WGM12// for Fast Pwm with TOP from OCR1A
    | 1;                      // Start timer 1 with prescale 1
  // Set OCR1A *after* setting up TCCR1A & TCCR1B
  OCR1A = 209;                // Gen. about 38095.24 Hz
  pinMode(OC1Apin, OUTPUT);
  interrupts();
}
void loop() {}

Edit 1: Here are some of the differences between this code and that shown in the question, aside from using timer 1 instead of 0:
• Initialization of TCCRxA and TCCRxB registers here is done using Register = expression forms, rather than  Register |= expression forms.  Just OR-ing your bits in may be a problem if some other CS bits are set.  For example, in the Arduino environment, initialization for millis() will set a prescale factor of 64, by setting both of the CS00 and CS01 bits, so that when you say TCCR0B |=(1<<WGM02) | (1<<CS01); you end up with both of the CS00 and CS01 bits still set, and a prescale of 64 instead of 8.
• TCCR1B = ... | 1;  // Start timer 1 with prescale 1 sets the CS00 bit and leaves the CS01 and CS02 bits clear, selecting prescale 1, while TCCR0B |= ... | (1<<CS01); selects a prescale factor greater than 1.
• The code shown here generates a square wave because it toggles a pin at a constant rate.  The code in the question sets OCR0B to 26, which will give 27 clock-cycles to half of each output cycle, and 26 clock-cycles to the other half.
• The code shown here generates a frequency of about 38095 Hz, which is about 0.25% high, vs a frequency 0.7% low for the code in the question.

Edit 2: One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle if appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:
volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

To output a specified number of cycles n, set the mode of TogPin to OUTPUT and set TogCounter to 2·n.  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.
To generate a sequence like m1 cycles on, n1 off, m2 cycles on, n2 off, etc, you could set up an array containing m1, n1, m2, n2, etc; then each time TogCounter runs down, toggle TogPin from INPUT to OUTPUT or vice versa, and load the next array entry into TogCounter.

I have analysed your code and to me it seems that , both are identical . Just that you have used timer 1 with no prescaler and therefore  OCR1A=209 , whereas I have used Timer 0 with Prescaler of 8 and therfore OCR0A = 51 (corrected) . Have i missed any changes that you have added ?

another thing that i have noticed is , you are setting the timer frquency to 238 Khz , so that on match you will just toggle the level ( using COM1A0) . I have done it differently by settng timer freq =38 Khz and instead of toggling , I am just setting it to 0 once half of that freq i.e 38 Khz is reached . thus , i will get On and Off freq = 382 Khz. thereby achieving what you have tried to do . Only difference is I am using OCR0B to output the pwm , as i did not want to change the value of OCR0A from the setup() part . I don't see anything that I have done differently than yours .

@BoudhayanDev, see edit 1

Okay so besides the Or operation mentioned in first point , what i need to change is - select Toggle mode using CS10/11/12 . I'll give it a try.
Also , i was thinking , I'll use ICR1 register to hold the Top value instead of OCR1A . so in that way OCR1A will be free to output the pwm wave . Is it fine if i do it or should i continue with OCR1A to hold the Top value and OCR1B to output the pwm wave ?

I'm not sure what you mean by  “output the PWM wave”; I thought you were trying to output a 38KHz square wave, which is what the code I posted should do.  With that code, one sets up the square wave frequency by the value in OCR1A, after which it rolls out a square wave on OC1A with no further program interaction needed.   Are you instead trying to put varying PWM modulation onto a 38KHz carrier, rather than genning a square wave?

Thanks for the explanation , your code works and so did my original code . Generating the 38Khz frequency worked with my original code by just replacing the OCR0A value to 51 instead of 52 as suggested .
However , your approach worked too . Only difference is the precision of the square wave .
Additionally , can you suggest a way to output only a certain number of pwm pulses . For ex - with the 38Khz wave that's generated , i want to output only 6 On-Off pulses of it followed by complete logic low . As in "fixed number" of 38Khz pwm pulses only and not continuous pulse train.

@BoudhayanDev, see edit 2

thanks it worked. I have just resettled CS pins after a specific period of time to 00 . That specific period of time during is the time  during which the pulses are generated .

A few ways to get there. 38khz has a period of 421 ticks on a 16mhz Mcu. So
Approach 1. Use the pwm module to Generate it.
Approach 2. Use the timer overflow interrupt to generate it. Simply flip the output pin in the isr.
Approach 3. Use the compare interrupt to generate it. In the isr increment the compare match register by 120 and then flip the output pin.
All of them are fully supported by your chip. The first approach once set consumes no CPU processing power.
edit: this link, https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/, will hopefully provide some inspiration to you. It is for a different application but the gist of the problem is the same.
here is the output, adopting it to generate a 38Khz (37,679Hz to be exact) pulse train on a user specified pin using timer2 compare ch b interrupt.

i think you will benefit a lot in getting the code going on your own but if you really struggle, I can provide you the code as well. but you get a lot more if you try to get it going on your own.

Can you elaborate your Approach 2 and 3 wit certain code examples ?


text:
How do i generate exact number of PWM pulses in arduino?
So my code here generates a PWM wave of 38Khz on Port B pin 7 of arduino Mega 2560 . For that I have used a prescaler of 8 and then set the ICR1 register value to 51 . I have also set the WGM10 ,WGM11, WGM12 and WGM13 bits to 1 , to enable fast PWM mode with Top reference value as ICR1 contents . Similarly , COM1A1  is set , to enable clear output on compare equal else high . CS11 is set to high to enable the prescaler 8 .
My code is as follows -
#include<avr/io.h>
#include <avr/iomxx0_1.h>
#include<util/delay.h>
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        TCCR1A =  (1<<WGM11) | (1<<WGM10) | (1<<COM1A1);
        TCCR1B =(1<<WGM12) | (1<<WGM13) | (1<<CS11);
        ICR1 = 51;
}

void pwm_generate()
{
    OCR1A = (50 * 52)/100 ;
}
int main()
{
pwm_init();
pwm_generate();
}

What I require from the program is that , it should stop producing pwm pulses once a sufficient number of pulses are transmitted . For example - The program should output 7 pwm pulses of 38Khz and then it should give logic 0 as output for specified time period . And then after that specified period , it should produce 38 Khz pwm wave again of say, 5 pulses and then again logic 0 for certain duration . And so on ...
How do i achieve this ?
PS- This program is actually being written to simulate a pwm wave required by the IR transmitters in TV remote . The PWM pulses represent the ON period and the Logic 0 conditions would represent the gap in between two successive train of PWM pulses.
Picture of waveform for reference -

There's a whole IRremote library to do that for you.

I don't want to use any libraries.

It's not the number of carrier cycles that matters but the time the pulses are on or off for _ and that not accurate to a pulse. The carrier is just to get the signal through a band-pass filter at the receiver end.

One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle, whichever is appropriate).  It can decrement a counter, and shut off an output pin when the counter gets to zero.  Or could set the output pin low and the CS bits to 0 to stop the counter.  For example, if timer 1 is in use:
volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

To output a specified number of cycles n, set the mode of TogPin to OUTPUT and set TogCounter to 2·n (or to n if counting cycles instead of toggles).  Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.
To generate a sequence like m1 cycles on, n1 off, m2 cycles on, n2 off, etc, you could set up an array containing m1, n1, m2, n2, etc; then each time TogCounter runs down, toggle TogPin from INPUT to OUTPUT or vice versa, and load the next array entry into TogCounter.

Thank you. I have used the CS reg to set the port to normal and forced logic 0 through it after specific number of pulses were generated . Though I haven't used interrupt , your explanation was helpful .

simple:
1) generate a pulse train of 38Khz -> many ways to do that;
2) put a resistor on the pulse train -> something like 1K will do it;
3) on the other end of the resistor, put a GPIO pin on it; configure it as input, but write a '0' to it;
4) route the clock input of a timer to that GPIO pin; set it to trigger an isr on a given number of pulses -> many ways to do that;
5) in the isr set up in 4), turn the gpio pin in 3) to output to disable the pulse train; input to enable the pulse train.
6) done.

Can you elaborate with the isr code example ?

source: Stack Exchange

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

sort: votes


text:
Motor running during Motor Shield R3 reset
I have a problem with the Arduino Motor Shield R3 on an Arduino Uno. I Have a DC Motor on the A Channel and the Shield is connected to an external power source. When I reset the Arduino card the motor starts running by default until the pins are initialized.
This is really problematic for me because the motor is on a rail delimited by 2 switches, when a switch is reached the motor stops. When the motor moves during reset the value of the switches are not read yet, which causes the motor to go beyond the switch and be blocked afterwards.
When I reset the card I read the value of the 3 digital pins used to drive the motor :

pin 12 : Direction (DirA), HIGH motor foward, LOW motor running backward
pin 3 : Power (PwmA), HIGH motor running, LOW motor not running
pin 9 : Brake (BrakeA), HIGH brake is on, motor can't run, LOW brake is off, motor can run

Before reseting I put the 3 pins at HIGH, At reset, pin 12 == HIGH, pin 9 == LOW, pin 3 == HIGH
which means that the brake is disengaged but the Power is still here, so the motor starts running again until the pinMode function is reached. During that reset time of approximately 2 seconds, the motor has the time to go beyond the switches which causes the system to break.
Is this normal ? Is there a way to force the pin 3 to be at LOW when the Arduino resets ? I put my code at the bottom.
Naïve solution : is to put PwmA at LOW when a switch is reached, so I'm sure it will stay that way until the next reset. But if the arduino is reseted while the motor is running I still have the problem.
int closeSwitch = A3;
int openSwitch = A2;
int DirA = 12;
int PwmA = 3;
int BrakeA = 9;

int OpeningDirection = LOW;
int ClosingDirection = HIGH;

bool motorRunning = false;
bool motorOpening = false;
bool openSwitchReached = false;
bool closeSwitchReached = false;

void setup() {

  Serial.begin(9600);

  sendToPC("Init\n"); //This is just to read the init state of the pins
  Serial.print(digitalRead(DirA));
  Serial.print(digitalRead(BrakeA));
  Serial.print(digitalRead(PwmA));

  pinMode(openSwitch, INPUT);//is High when Hublot opened
  pinMode(closeSwitch, INPUT); //is HIGH when hublot closed
  pinMode(DirA, OUTPUT); //Initiates Motor Channel A pin
  pinMode(BrakeA, OUTPUT); //Initiates Brake Channel A pin
  pinMode(PwmA, OUTPUT); //Initiates Brake Channel A pin

  sendToPC("\nAfter\nA:"); //After init all is LOW
  Serial.print(digitalRead(DirA));
  Serial.print(digitalRead(BrakeA));
  Serial.print(digitalRead(PwmA));

  //Stopping the motor
  setMotorSpeed(0);
  if (digitalRead(BrakeA) == LOW) {
    brakeMotor();
  }

  //Is the first switch on
  openSwitchReached = (digitalRead(openSwitch) == HIGH);
  //Second switch state
  closeSwitchReached = (digitalRead(closeSwitch) == HIGH);

  handleSerialInput(-3); //Send ping return
  handleSerialInput(-2); //Send status
}

void sendToPC(const char * str) {
  Serial.write(str);
  delay(215); //Delay to avoid answers being read as one
}

void setMotorSpeed(int speed) {
  if (speed > 0)
    digitalWrite(BrakeA, LOW);   //Disengage the Brake for Channel A
  digitalWrite(PwmA, HIGH);   //Spins the motor on Channel A at full speed
}

void setMotorDirection(int direction) {
  digitalWrite(DirA, direction); //Establishes direction of Channel A
}

void brakeMotor() {
  digitalWrite(BrakeA, HIGH);
  //digitalWrite(PwmA, LOW); -> this is my naïve solution
}

void handleSerialInput(int input) {
  Serial.print(input);
  if (input == 1 && !openSwitchReached) { //open
    brakeMotor(); // stop motor
    delay(100);
    setMotorDirection(OpeningDirection);
    setMotorSpeed(255); // set motor max speed
    motorRunning = true;
    motorOpening = true;
    sendToPC("HublotOpening");
  }
  else if (input == 2 && !closeSwitchReached) { //close
    brakeMotor(); // stop motor
    delay(100);
    setMotorDirection(ClosingDirection);
    setMotorSpeed(255); // set motor max speed
    motorRunning = true;
    motorOpening = false;
    sendToPC("HublotClosing");
  }
  else if (input == -2) { //get status
    if (openSwitchReached)
      sendToPC("HublotOpened");
    else if (closeSwitchReached)
      sendToPC("HublotClosed");
    else if (motorRunning && motorOpening)
      sendToPC("HublotOpening");
    else if (motorRunning && !motorOpening)
      sendToPC("HublotClosing");
    else if (!motorRunning)
      sendToPC("HublotNotMoving");
  }
  else if (input == -3) //Ping
    sendToPC("ArduinoHublot");
  else if (input == 0) { //Stop
    brakeMotor(); // set motor max speed
    motorRunning = false;
  }
  else {
    sendToPC("WTF");
    Serial.print(input);
  }
}

void loop() {

  openSwitchReached = (digitalRead(openSwitch) == HIGH);
  closeSwitchReached = (digitalRead(closeSwitch) == HIGH);

  if (openSwitchReached && motorRunning && motorOpening) {
    sendToPC("HublotOpened");
    brakeMotor();
    motorRunning = false;
    delay(200);
  }
  else if (closeSwitchReached && motorRunning && !motorOpening) {
    sendToPC("HublotClosed");
    brakeMotor();
    motorRunning = false;
  }

  if (Serial.available()) {
    int read = (Serial.readStringUntil(':')).toInt();
    handleSerialInput(read);
  }

}

Add pulldown resistors (10KΩ) to any pins you want to force to be low at reset.
(Quite frankly I'm amazed they don't exist on all inputs to the board by default - it seems a bit of a fatal omission).

According to this that's what they done for BrakeA, I will try it. Thanks for the answer.

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


text:
Simple Ground circuit layout
I am making a circuit without using a PCB or perfboard and i am unsure if i am running the ground wire correctly.

I usually prototype on a breadboard with the ground all joining on the far right, is this the same concept? I wanted to know if this is the accepted  convention for running the ground back to the board.

For a basic circuit like this you don't need to worry terribly about the grounding details. It's when you have higher speed and more complex signaling that it really matters.

@IgnacioVazquez-Abrams My final circuit is utilizing 20 pins running 2 LEDs each in parallel on a blinking program. Does that fall into the "complicated" category or is that still on the simpler side? No motors, rotors, ICs, isensors, Etc

The only problem I see is running two leds at (looking at the resistor value) 20mA each on only one pin. 40mA is the absolute maximum rating of a pin. 20mA is generally advised. There is also a maximum current per section of pins (see datasheet). So depending on the pattern of lights, you might run into a limit there.

Consider using a LED driver chip instead, running the LEDs in series with a higher voltage.

Further to the above point. 20pins at 40mA (ie: all lights on) is 800mA which is more than the micro can safely source.

Just because i don't understand completely, if i use an LED driver with the arduino would that solve the mA limitations and if so how?

@Mazaryk I outlined that limit yesterday at the OP's other question. I wonder if we should try to keep the whole issue in one question or rehash it over in (now) three...

Hey @Ghanima, yea this circuit keeps bringing conversations back to the inevitable question of power. All i wanted to know was if the ground wire is run correctly which they answered here. I figured if i simplified the question, i could get it answered, but i suppose I really need to rethink this circuit if it keeps raising red flags.

Yes, based on basic electrical theory, you have the ground connected correctly.


text:
Using two ultrasonic sensors together
Using two ultrasonic sensors together, how can I enable one before the other?

Do you have a circuit?  Any code?

You need to tell the sensor to send their pulse using the trigger line.  So triggering isn't a problem.
The problem is that you might get an echo returned on both sensors, but you know which sensor sent the pulse so you can ignore the return that was received by the 'wrong' sensor in your code.
So
While(1)
{
  SendPulse(SensorTx1);
  GetEcho(SensorRx1);
  SendPulse(SensorTx2);
  GetEcho(SensorRx2);
}

Is that what you mean?  If not please can you expand you question?


text:
DHT11 sensor not working on ESP8266, no response
recently Ive set up an ESP8266 to control temperature and humidity in rooms, for this Im using DHT11 sensor, thats the basic code I have in order to check functionality in Arduino IDE
#include "DHT.h"
#define DHTPIN A0
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHT11 Testprogram");
  dht.begin();
}
void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println("Error");
    return;
  }

  Serial.print("Luftfeuchtigkeit: ");
  Serial.print(h);
  Serial.print("%\t");
  Serial.print("Temperatur: ");
  Serial.print(t);
  Serial.write('°');
  Serial.println("C");
}

So far as I've checked the code seems to be all right and doesn't have any issues. The bottleneck might be the circuit although I checked twice and I don't really understand what the issue still might be.

the 3V is connected to the + and to the pull up resistor of the sensor which is 10K and A0 Pin according to the plan with data pin of the sensor as well as with a pull up resistor and G is connected to - of the sensor. I still get no response from the sensor, I even checked other 3 sensors and cannot understand what the issue might be, does anyone know a solution?

DHT on A0? A0 is only analog input

Well as far as I've read, it's also possible to use A0 on esp8266 as input

analog input or for button. but not for digital communication. and I think A0 on nodemcu is directly connected to esp8266 analog input which is 0 to 1 V

I tried also digital inputs, it's still the same issue, I get NaN as response

What digital inputs did you try? Have you tried other DHT libraries (the one from Adafruit for example)? It’s hard to make out the connections from your photo by the way.

I tried all of them it didnt work, I used grove humidity sensor library but I might have a look if another library gonna do some magic

Try the "DHT for ESP" library.

tried other libraries as well, still no success, I was thinking that the resistor might be an issue or some kind of other electronic part

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


text:
What components I need for a small GPS tracker
I am new to Arduino and want to create a graduation project for my university.
I am thinking to create a GPS tracker that can be attached to a cloth to track kids, for example.
So the requirements for this project is as follows:
- The device should be small
- It should upload its location to a web server constantly.
- the device should work with battery for at least 8 hours
Now what components are needed for this project?
What concern me a lot is that how can I find battery last this much time, if I need bigger battery, it may hinder the device from being attached easily.

There's a device you can buy off the shelf that can do all this already: it's called a mobile phone.  The kids most probably already have one.

An arduino is a bad choice for this project, as it will lock you into using a larger, more expensive "hacker friendly" form of the GPS and data uplink (GSM or whatever) functions than would be used by an existing all-in-one solution.

It sounds like he is supposed to make the project, not buy a phone off the shelf.

Apparently OP want the device to be small & mobile phone nowdays is 5/6 inch

Guys as Nick said I need to make the project for learning not buy a complete solution, I don't need to track my kids I just gave you an example

you just need this https://ru.aliexpress.com/item/33045644281.html this module has ESP32 Wireless Module GPRS Antenna SIM Card SIM800L GPS apart from this you need a sim card/wifi internet , some wires, and power source i guesss 3.3v then you are ready to go

In addition to @Majenko's post, you will save considerable power by turning the GPS & GSM off when not needed - for example, you might decide that once per minute, or once per 5 minutes is enough (maybe send it a text to trigger "continuous mode"?). Once the Arduino has switched off the other devices, it can go into "sleep" mode for a while. Check out Nick Gammon's excellent treatise on power saving modes at http://www.gammon.com.au/power
You can save both power and size by replacing an entire Arduino with an ATTiny - prototype on an Arduino first, then once it's working, move to an AtTiny - they have fewer pins, less memory, and are cheaper & smaller.
I doubt you could get the size smaller than a small cellphone, which can be had for very little - $35ish plus shipping, from http://www.aliexpress.com/item/Cheap-original-Mobile-phone-LG-Optimus-One-P500-WIFI-GPS-JAVA-Android-OS-Unlocked-Mobile-Phone/32274282341.html?spm=2114.01020208.3.1.zgFwLV&ws_ab_test=searchweb201556_1,searchweb201527_3_71_72_73_74_75,searchweb201560_9

GPS takes a potentially significant time to regain satellits depending on how long it is off and where satelllites are. Maintaining an emphemeris or even producing an active one would help minimise acquistion time.

Generally, GPS' store their ephemerides, and/or they can be downloaded from the GPS. You may wish to test this - get a lock, power everything down, then power everything up, and time how long it takes to get a positive location. Ephemerides are valid for an hour, and GPS' come in and go out of view. Nevertheless, you will still use less power waiting for the download than you would leaving it on. If you are only polling once an hour, it may be worth polling every 55 minutes instead.

Ephemerides don't take longer to expire if you keep using them, you just get a new download before the old one has gone - this takes the same time as it would to get one after it has expired.

Further research shows ephemerides are valid for 4-6 hours, and are updated every 2 hours. Same applies - If you get a lock every hour-and-one-second, and shut down in between, you should need to download ephemerides at the 6 hour 6 second mark; if you get a lock every 59:59 minutes, you will need to download new ephemerides at 6:59:53. This may vary due to different satelites being visible, and from receiver to receiver.

You need four things:

A GPS receiver
A GSM modem
An Arduino
A Battery

Using off the shelf products you would probably end up with something about the size of a cigarette packet at best - probably bigger.
To make it small enough to be unobtrusive would take a lot of work.  You would need to design your own circuitry combining everything that is contained in the three circuits above into the smallest design you can, and since most existing solutions use pre-built modules (cans) that are relatively large you would first have to discover how they work and replicate them as one single tiny module.
And then there is the battery.  GPS receivers are very sensitive devices. They have quite powerful preamplifiers to detect the incredibly faint signals of the satellites.  Consequently they use quite a bit of power.  Similarly GSM modems are quite power hungry, especially when they are far from a cell tower.
Put those together and you have quite large power requirements - so the battery will consequently be relatively large.  Many times the size of the circuit you designed above.
So if you're trying to make something that James Bond might stick on the back of someone's jumper without them noticing you're very much out of luck I'm afraid.
That is why most tracking of people is done using a larger device that most people have sat in their pocket already: a mobile phone.  You can already get software for most phones that will allow you to track your children.

You have two options. Option 1. Buy a ready made pet tracking device from online market e.g (https://www.aliexpress.com/item/Pets-Smart-Mini-GPS-Tracker-Anti-Lost-Waterproof-Bluetooth-Tracer-For-Pet-Dog-Cat-Keys-Wallet/32887784462.html?spm=2114.search0104.3.1.26793604pFMLma&ws_ab_test=searchweb0_0,searchweb201602_3_10065_10068_319_10059_10884_317_10887_10696_321_322_10084_453_10083_454_10103_10618_10307_537_536,searchweb201603_52,ppcSwitch_0&algo_expid=09c58262-a0e7-4205-8fba-cd8265c15b3e-0&algo_pvid=09c58262-a0e7-4205-8fba-cd8265c15b3e). Then you can download the app and start tracking movement.
Option 2: The other alternative is to build one from scratch by purchasing all the necessary components. This is option is most appropriate for students. You can check this page for more https://electronicsforu.com/electronics-projects/hardware-diy/gsm-gps-based-vehicle-tracking-system. However, you may not be able to achieve the small size as you wanted but you should have something close to it if you carefully select your components.

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


text:
Where do I get motion detector for ardruino that can actually be installed in ceiling?
This might be a bit of off topic but I have nowhere else to go. :-) I have programmed motion detection with ardruino and would like to integrate it with my home automation system.
Would like to install the PIR in the ceiling of the entrance.
The problem is that all low voltage PIRs for ardruino are sold without any case (just a board).
Does it mean I have to buy a regular PIR (with relay integrated) and modify it?

Why do you feel the need to modify it?

I bought a regular PIR (with 220V relay) and as I remember well motion detection board needs higher voltage than what ardruino can supply 3.3V and 5V.

So supply it with that higher voltage then.

I would rather avoid it but it looks like there is no other way.

This might not be quite the answer you were looking for, but...
3D print your case.
I expect you haven't got a 3D printer but you can find someone on 3D hubs to print it for you, and you might not even have to design the case because thingiverse has a few already...

Try looking at Alarm PID units, they typically will operate on 12VDC and have a relay output contact and a tamper contact.  They are not that expensive and come with a case.
Gil


text:
How to wire an LMD18200 and an arduino?
Ive been working with a motor project for a while and i bought this H-bridge(LMD18200). I dont understand how im supposed to connect it to the arduino.
Here is the datasheet for the lmd18200:


text:
Arduino WIFI compiler error
Just bought an ESP8266 module to try it using my arduino uno R3. I have connected my WIFI module correctly, anyways evenb if i disconnect it, the error occur.
While trying to upload the WIFI (connect with wpa) sketch i get several errors.
First i tried uploading the hole sketch, i got those errors:
/usr/share/arduino/libraries/WiFi/WiFi.cpp: In member function ‘uint8_t* WiFiClass::macAddress(uint8_t*)’:
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: unable to find a register to spill in class ‘POINTER_REGS’
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: this is the insn:
(insn 35 25 26 2 (set (reg:QI 23 r23)
    (mem/c:QI (plus:HI (reg/f:HI 28 r28)
            (const_int 2 [0x2])) [3 S1 A8])) /usr/share/arduino/libraries/WiFi/WiFi.cpp:110 28 {movqi_insn}
     (nil))
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112: confused by earlier errors, bailing out

After that i tried to only import just the libraries and try to compile it. Even with this method i get errors
Code
#include <WiFiServer.h>
#include <WiFiClient.h>
#include <WiFi.h>

error:
In file included from /usr/share/arduino/libraries/WiFi/WiFiServer.h:8:0,
                 from sketch_oct20b.ino:1:
/usr/share/arduino/hardware/arduino/cores/arduino/Server.h:4:29: error: expected class-name before ‘{’ token
In file included from sketch_oct20b.ino:1:0:
/usr/share/arduino/libraries/WiFi/WiFiServer.h:14:3: error: ‘uint16_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:17:22: error: field ‘uint16_t’ has incomplete type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:18:24: error: ‘uint8_t’ has not been declared
/usr/share/arduino/libraries/WiFi/WiFiServer.h:20:11: error: ‘size_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:21:11: error: ‘size_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:22:3: error: ‘uint8_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:24:9: error: ‘Print’ has not been declared
/usr/share/arduino/libraries/WiFi/WiFiServer.h:18:42: error: ‘NULL’ was not declared in this scope

I can just figure out some syntax errors, but my c is not good enough to understand much of it.
Can anyone tell me what am i doing wrong and show me how it will be done?

The WiFi libraries (such as Wifi.h, WifiClient.h, and WiFiServer.h) are used for interfacing with the official Arduino WiFi shield. Interfacing with an ESP8266 module is typically done by issuing AT commands via UART (i.e. Serial.write(), etc.)

Nice one, thank you sir. That means i need an additional FTDI breakout board and a logic level shifter, right?

Logic shifter yes, the UNO is a 5 volt device and the ESP8266 is a 3.3 volt device. FTDI probably not, you can communicate to the ESP8266 via the UART pins (0 and 1), and even if you need to update the firmware ofr the ESP, you can do that by pulling the microcontroller out of the socket and just use the board as a USB to Serial adapter.


text:
Rc car which returns to middle when left or right button is not pressed
Hi i am currently working on a school project , my only problem is that i want my RC car to return to middle direction (which i have set to 66 in the servo motor) when the left or right button is not pressed . i used if statements but it doesn't work. Are there any function that i can use ?
Here is my code for the transmitter i used the RC-Switch Library (https://www.arduinolibraries.info/libraries/rc-switch)
#include <RCSwitch.h>
#include <Servo.h>

const int IN1 = 3;
const int IN2 = 4;
const int trigPin = 5;
const int echoPin = 6;
const int Buzzer = 8;
int distance = 0;
int value = 0;
long duration;
RCSwitch mySwitch = RCSwitch();
Servo myservo;

void setup () {
  mySwitch.enableReceive(0);
  myservo.attach(7);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(Buzzer,OUTPUT);
  Serial.begin (9600);    // Debugging only
  Serial.println ("Receiver Ready");
}

void loop () {

  delayMicroseconds(10);
  // 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;
  // Prints the distance on the Serial Monitor
  //Serial.print("Distance: ");
  //Serial.println(distance); //distance is the returned integer,

 if (mySwitch.available()) {

    value = mySwitch.getReceivedValue();
    Serial.println (value);

      if(value == 1) {
        forward ();
        Serial.println (" = forward");
      }

      if(value == 2){
        backward ();
        Serial.println (" = backward");
      }

      if(value == 3) {
        left ();
        Serial.println (" = left");
      }

      if(value == 4) {
        right ();
        Serial.println (" = right");
      }
      Serial.print(" ");
    }
  mySwitch.resetAvailable();
  //myservo.write(45);
}

void forward () {
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}

//value = mySwitch.getReceivedValue();
void backward () {

  if ((distance < 50)&& (value == '2'))
  {
    digitalWrite (IN1, LOW);
    digitalWrite (IN2, LOW);
    digitalWrite (Buzzer, HIGH);
  }
  else if ((distance > 50)&& (value == '2'))
  {
    digitalWrite (IN1, HIGH);
    digitalWrite (IN2, LOW);
    digitalWrite (Buzzer, LOW);
  }
}
// 66 is middle

void right () {
  if (value == 4){
    myservo.write(110);
  } else
  myservo.write(66);
}

void left () {
  if (value == 3){
    myservo.write(50);
  }else
 myservo.write(66);
}

And Here is The transmitter code
// TRANSMITTER CODE

#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
// Assigning controller buttons to Digital Pins
 int forward = 11;
 int reverse = 10;
 int rightTurn = 9;
 int leftTurn = 8;

void setup () {
  pinMode (forward, INPUT_PULLUP);
  pinMode (reverse, INPUT_PULLUP);
  pinMode (rightTurn, INPUT_PULLUP);
  pinMode (leftTurn, INPUT_PULLUP);
  mySwitch.enableTransmit(7);
  Serial.begin (9600);         // Debugging only
  Serial.println ("Transmitting");
}

void loop () {
  if (digitalRead(forward) == LOW) {
    mySwitch.send(1, 24);
    Serial.println ("Forward");
  }

  if (digitalRead(reverse) == LOW) {
    mySwitch.send(2, 24);
    Serial.println ("Reverse");
  }

  if (digitalRead(leftTurn) == LOW) {
    mySwitch.send(3, 24);
    Serial.println ("Left Turn");
  }

  if (digitalRead(rightTurn) == LOW) {
    mySwitch.send(4, 24);
    Serial.println ("Right Turn");
  }
}

do not use statements such as but it doesn't work .... there is no useful information contained in such statements ...... statements such as it keeps turning left, actually describe what is happening

You send values from your transmitter when you press a button but not when you release them. The simplest solution would be sending the state of all buttons in every iteration if the transmitter has enough capacity. (I think it has for just these four values)
Add an enum to make the code more readable:
enum {
    FORWARD_ON = 0,
    FORWARD_OFF, // It will be 1.
    BACKWARD_ON, // It will be 2 and so on...
    BACKWARD_OFF,
    RIGHT_ON,
    RIGHT_OFF,
    LEFT_ON,
    LEFT_OFF
};

So a sending function will be like this:
if (digitalRead(forward) == LOW)
    mySwitch.send(FORWARD_ON, 24);
else
    mySwitch.send(FORWARD_OFF, 24);
// And so on for every button...

Then by reception you should add some state variables and store the received values:
int steer_right = 0;
int steer_left = 0;

// ...

loop() {

// ...

value = mySwitch.getReceivedValue();

switch (value) {
    case RIGHT_ON:
        steer_right = 1;
        break;
    case RIGHT_OFF:
        steer_right = 0;
        break;
    case LEFT_ON:
        steer_left = 1;
        break;
    case LEFT_OFF:
        steer_left = 0;
        break;

    // ... (throttle)

    default:
        break;
}

// ...

}

Then you evaluate what you got:
if (steer_right && !steer_left)
    right();
else if (!steer_right && steer_left)
    left();
else
    straight();

// ... (throttle)

Hi it's me again, I'm a bit confused at the switch (value) part , should i declare the RIGHT_ON and RIGHT_OFF as variables or enum them ?

and also is there anyway i can speed up the sending speed?

another question is it keeps printing when the button is off which i think is the cause why it's slow to send and receive , is there any way i can prevent this ?

keeps printing what? ..... do not print when the button is not pressed (use if statement or case statement )


text:
I am in need of a usable communication library on 1-4 pins of ATTiny84 instead of I2C
I messed up when designing my PCB and just assumed that I could use software slave I2C with ATTiny84.
The reason I did so is - I needed to use all of the analog inputs.

The pins I have on my connector are:
PB0 (pin 2), PB1 (pin 3), PB2 (pin 5) and PA0 (pin 13)
Is there an alternative to I2C or a different communication protocol I could use to connect multiple of these slave boards to a master (ATMEGA328 etc.)?
Thanks a lot, I can provide any further information.

SPI without MOSI (one-way comms) only needs two pins CLK & MISO. That saves you one pin.

You can write a bit-banging implementation of I2C. -- As well as any other serial protocol. -- You could even invent your own protocol, but this is not wise. -- There are many serial protocols, starting with 1 wire.

That is a lot of pins, so this really boils down to your application and what you want to optimize for.
You could do a bit-banged software I2C slave on these pins. "Bit-bang" means you just write a program to flip the bits on the pins rather than handing the bytes off to the hardware which would do the same thing (although sometimes faster or without using up CPU cycles). This would require either finding some existing code to implement the protocol, or sitting down with the documentation for the protocol and writing it yourself. Depending on your goals, the second option might be a great learning experience and take away some of the magic from this stuff. It is all just 1s and 0s and once you really internalize that, you realize that you can do almost anything with these little chips regardless of hardware or library support.


text:
Unable to initialize SD card
I am not able to initialize the SD card. Can't find figure out what the issue is. It fails at the condition
if (!SD.begin(D8)) {
Serial.println("initialization failed!");
return;
}

I am using D1 Mini V2 board and standard SD card module. Pin configuration attached with images below.

Connections are -
GND => GND
VCC => 3.3V
MISO => D6
MOSI => D7
SCK => D5
CS => D8
Code is -
#include <SPI.h>
#include <SD.h>

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);

  Serial.print("Initializing SD card...");

  if (!SD.begin(D8)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

Did you try different SD cards? (preferably smaller older ones, as SDXH for example might not work).

I am using Kingston microSD card

Is it not an SDHC or SDXH card? And did you try it with a default example?

The code copied above is the default example!

I expect the SD card is not supported than. I used a simpler SD card reader for the Uno and it could only read (old) upto 2 GB SD cards.

I myself am using 2gb card. Do you see any error in the code/connection?

this is a 5 V adapter. you have a 3.3 V board

Yep!!, that fixed it, changed VCC=> 5V and it solved the issue. Thanks @Juraj

but you don't need a logic level conversion between esp8266 and SD card adapter. https://i.sstatic.net/urotx.jpg

Use "SdFat" library.


text:
Timer interrupt triggers too often
The following question is based on the Arduino Pro Mini (8MHz, 3.3V)
I'm in process of developing (yet another) LED strip driver shield. For that I wrote a simple control loop, that adjusts the channel brightness (PWM duty cycle) to a given target value with a smooth transition.
For testing purposes I configured Timer1 with a 0.5Hz interval to randomly assign new target values. This works almost as intended. When watching the values you can see the constant value periods and completely random, fast changing periods in between (picture generated with Arduino built-in plot). The curved, rather smooth lines are the PWM outputs following the target value (that part is confirmed to work):

The relevant code responsible for the changing of the target value is
ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
{
  for(auto it = 0; it < 4; ++it)
        channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
}

My assumption is, that the ISR is called very fast in the fuzzy intervals but since I havn't done much with arduinos yet, I'm not familiar on what kind of background functions might interfere with that.
For completeness the full code:
double          channel[4];
uint8_t         channel_target[4];
const double    channel_k_p[4]      = { 0.001, 0.001, 0.001, 0.001 };
const double    channel_k_i[4]      = { 0.01, 0.01, 0.01, 0.01 };
double          err;
const uint8_t   led_pins[4]         = { 3, 5, 6, 9 };
char            serial_buffer[100];

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

    for(auto it = 0; it < 4; ++it)
        channel[it] = 0;

    for(auto it = 0; it < 4; ++it)
    {
        pinMode(led_pins[it], OUTPUT);   // sets the pin as output
        analogWrite(led_pins[it], 0);
    }

    cli();//stop interrupts

    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1  = 0;//initialize counter value to 0
    // set compare match register for 1hz increments
    OCR1A = 15624;// = (8*10^6) / (0.5*1024) - 1 (must be <65536)
    // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);

    //set timer2 interrupt at 500Hz
    TCCR2A = 0;// set entire TCCR2A register to 0
    TCCR2B = 0;// same for TCCR2B
    TCNT2  = 0;//initialize counter value to 0
    // set compare match register for 8khz increments
    OCR2A = 248;// = (8*10^6) / (500*64) - 1 (must be <256)
    // turn on CTC mode
    TCCR2A |= (1 << WGM21);
    // Set CS21 bit for 64 prescaler
    TCCR2B |= (1 << CS21) | (1 << CS20);
    // enable timer compare interrupt
    TIMSK2 |= (1 << OCIE2A);

    sei();  // reactivate interrupts

    randomSeed(analogRead(0));
}

void loop()
{
    for(auto it = 0; it < 4; ++it)
    {
        sprintf(serial_buffer, "%d ",  channel_target[it]);
        Serial.write(serial_buffer);
    }

    for(auto it = 0; it < 4; ++it)
    {
        sprintf(serial_buffer, "%d ", round(channel[it]));
        Serial.write(serial_buffer);
  }
    Serial.write("\n");

    delay(100);
}

ISR(TIMER2_COMPA_vect)  // timer2 interrupt at 1kHz
{
    // ******************************
    // Channel brightness control loop
    for(auto it = 0; it < 4; ++it)
    {
        err = channel_target[it] - channel[it];

        channel[it] += err * channel_k_p[it];           // proportional
        channel[it] -= err * 0.002 * channel_k_p[it];   // integral

        if(channel[it] > 255)
            channel[it] = 255;
        analogWrite(led_pins[it], floor(channel[it]));
    }
}

ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
{
  for(auto it = 0; it < 4; ++it)
        channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
}

Setting the timer register to 0 as the first ISR instruction or deactivating interrupts with
cli();
/* ISR code */
sei();
does not help.

Arduino code doesn't give you an easy control over all interrupts. In this case there is a possibility that Serial.write makes mess with interrupts. I would recommend to take a closer look at this. Also delay() is based on some interrupts.

The analogWrite() function generates a PWM output signal using a
hardware timer. Output on pin 3 is driven by timer 2, whereas
output on pin 9 is driven by timer 1. Here, you are trying to
use these timers for PWM generation and for your own code timing at
the same time. This cannot work. Either you let the Arduino core library
use the timers for analogWrite(), or you take them for you, but not
both.
The solution to your problem is very simple. Nothing in your code really
requires a timer to start with. You can handle both the brightness
control loop and the value changes using the technique of the Blink
Without Delay Arduino tutorial:
const uint32_t TARGET_CHANGE_PERIOD = 500000;
const uint32_t BRIGHTNESS_UPDATE_PERIOD = 1000;

void loop()
{
    uint32_t now = micros();
    static uint32_t last_target_change;
    if (now - last_target_change >= TARGET_CHANGE_PERIOD) {
        last_target_change += TARGET_CHANGE_PERIOD;
        // Change the brightness targets.
    }
    static uint32_t last_brightness_update;
    if (now - last_brightness_update >= BRIGHTNESS_UPDATE_PERIOD) {
        last_brightness_update += BRIGHTNESS_UPDATE_PERIOD;
        // Update the channel brightnesses.
    }
}

Thank you very much.
Is there a documentation for the timer usage somewhere (which timer is used by the arduino system for what)? I knew there are some parts of the arduino system that use various hardware timer, but except the dealy()/millis() <-> timer0 connection I couln't find any information in that regard.

@Patrick: The only authoritative info is probably the source code. It shows timer 0 is used for timekeeping and all three timers for PWM. To match pins to timers, see for example this pinout diagram. Every PWM-capable pin has a label “OCnx”, where n is the timer number (0 – 2) and x is the timer's channel (A or B).


text:
Arduino/ESP8266 - TCP server, connect to AP, receive connections/data
We're trying to use an ESP8266/Arduino Uno as a TCP server, which connects to a wireless AP and then receives commands from other devices on the same network. Currently we got the "connect to AP" part working, but when we try to send data to the ESP/Arduino/TCP server, it doesn't work, refusing all connections to it.
Here's the (relevant parts of the) code we currently use:
#include <SoftwareSerial.h>

SoftwareSerial ESPSerial(2, 3);

void setup() {
    Serial.begin(9600);
    ESPSerial.begin(115200);
    sendToWifi("AT", 10, true);
    sendToWifi("AT+CWMODE=1", 10, true);
    sendToWifi("AT+CWJAP=\""+myAp+"\",\""+myApPassword+"\"", 10, true);
    sendToWifi("AT+CIPMUX=1", 10, true);
    sendToWifi("AT+CIPSERVER=1,80", 10, true);
}

void loop() {
    // The code that would receive data from connecting devices are here
}

String sendToWifi(String command, const int timeout, boolean debug) {
    String response = "";
    ESPSerial.println(command);
    long int time = millis();
    while((time+timeout) > millis) {
        while(ESPSerial.available()) {
            char c = ESPSerial.read();
            response+=c;
        }
    }
    if(debug) {
        Serial.println(response);
    }
    return response;
}

I also have code that's supposed to receive/print data received from the other devices on the network but because no other device can even connect to this TCP server, I felt it was irrelevant for the question. If however you think it's important to include said code, let me know and I'll update my question.
All the solutions we've found online either configures the ESP as the AP, uses the WifiClient library, which we can't seem to get working (even if we could though, we'd rather do it through AT commands) or uses the ESP8266 as a stand-alone module.

and the prints in Serial Monitor indicate the the server started? can you ping the esp8266?

in general, these things are 10x easier to code/debug when you program the ESP directly in ardunio instead of using AT commands. you can then use the uno as the "slave", which makes sense anyway because it's a lot weaker than the ESP.

Did you get any solution? I am facing the same issue…


text:
stk500 getsync() attempt 10 of 10 atmega328pu
I've been getting this very common error on my atmega328pu circuit.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x83
Some things iv'e tried are:

Restarting my comp
Reuploading the bootloader
Redownloading old version of arduino IDE
Using an FTDI chip and placing the chip inside an Uno

After I bootloaded the chip I was able to upload a blink sketch. Then the next time I tried I got this error. Anyone know what could be up? This is driving me crazy!

Where is the edge detector on the reset line? Where are the decoupling caps?

https://arduino.stackexchange.com/a/22541/11529 Does this answer help?


text:
SoftwareSerial data being corrupted - looking for suggestions
I'm having problems running a serial communication between a NodeMCU ESP8266 and an Arduino Uno. I'm using the "standard" SUART setup, i.e. pins D1&D2 on the ESP are hooked up with GPIOs 2&3 on the UNO; the tx from UNO to ESP is fed through a voltage divider to step it down to 3.3V.
The setup used to work fine; suddently - yeah I've read it before, my setup suddently doesn't work, but honestly that's what happened - data is being corrupted.
The devices exchange a json formatted string:
{"action":"position","lat":123,"lon":123}

and it just worked. Now what I receive is something like:
{"⸮⸮⸮⸮⸮⸮":"pos⸮⸮⸮onb,"l⸮tF:0,"lo⸮":0,"⸮⸮s⸮⸮":0⸮

Both SUART are on 115200 baudrate, physical connections have been checked and are fine, both devices are grounded on the same reference level.
I've tried swapping the ESP with another one and changing TX/RX pins on the UNO - no results.
So I'm looking for suggestions what to do next to debug the issue, what to check and what could be wrong. Thank you in advance.
Below are UNO and ESP code snippets.
ESP8266
SoftwareSerial SUART(4, 5);

int16_t last_fetch = 0;
int16_t last_serial = 0;

double azimut, elevation;

#define DATA_FETCH_TIME_INT 3
#define SERIAL_TRASMISSION_TIME_INT 5

void setup() {
  Serial.begin(115200);  //enable Serial Monitor
  SUART.begin(115200);   //enable SUART Port

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println(WiFi.localIP());
}

void loop() {
  if (secs() - last_fetch >= DATA_FETCH_TIME_INT) {
    last_fetch = secs();
    fetchData();
  }

  if (secs() - last_serial >= SERIAL_TRASMISSION_TIME_INT) {
    last_serial = secs();
    sendDataViaSerial();
    }
}

void fetchData() {
  //connects to server and fetches data
}

void sendDataViaSerial() {
  int lat_i = (int) elevation;
  int lon_i = (int) azimut;
  int checksum = lat_i + lon_i;

  const int capacity = 200;
  StaticJsonDocument<capacity> doc;

  doc["action"] = "position";
  doc["lat"] = lat_i;
  doc["lon"] = lon_i;
  doc["cksum"] = checksum;

  Serial.println("Sending data via serial: ");
  serializeJson(doc, Serial);

  //SUART.flush();
  //serializeJson(doc, SUART);
  // works the same

  String outstring;
  serializeJson(doc, outstring);
  SUART.println(outstring);
}

ARDUINO UNO
SoftwareSerial SUART(2, 3);
#define arraySize 150
char inData[arraySize];

void setup() {
  pinMode(STATUS_LED, OUTPUT);
  digitalWrite(STATUS_LED, HIGH);

  Serial.begin(115200);
  SUART.begin(115200);

  Serial.println("Ready to go.\n");
}

void loop() {
  readSerial();
}

void readSerial() {
  short index = 0;
  char inChar;

  if (SUART.available() > 0) {
    while (SUART.available() > 0 && index < arraySize - 1) {
      inChar = SUART.read();
      inData[index] = inChar;

      index++;
      inData[index] = '\0';  // Add a null at the end
    }

    SUART.flush();
    String myData = (String)inData;
    Serial.println(myData);

    // consume data
    //parseIncomingData(inData);
  }
}

use 9600 baud. AVR SoftwareSerial can't reliably listen at 115200 baud

I have used SoftwareSerial for MIDI (which is 31.250 baud) and it didn't work reliable, so indeed 9600 seems a good starting point, probably you cannot go  much higher.

As @Juraj mentions in the comments, don't use 115200 baud with SoftwareSerial.
The problem is that the AVR isn't fast enough to handle incoming data at that speed reliably.  Yes, it can receive a byte fine at that speed, but what it can't necessarily do is store that byte away in the receive buffer in time to be ready to receive the next byte - so it misses the first few bits and corruption ensues.
Running at a lower baud rate (such as 9600 baud) simply gives it more time to process the data as it arrives.

Both you and @Juraj were right. So.. thanks!
Lowering the baudrate (now using 38400) fixed the corruption problem. However, adding delay(5); at the end of the receiver while loop seems to help as well. Again, thanks guys. Remains to be seen why it worked at 115200 and then suddently stopped.


text:
Cannot connect device with nRF8001 Bluetooth LE to Windows 10 PC
I've built a device using an IMUduino board, which is supposed to be similar to Arduino Leonardo board with a nRF8001 bluetooth. I was able to connect my device to an Android phone using the nRF UART v2.0 app, I tested some examples and it worked with success.
I would like to connect the device to a Windows 10 PC via bluetooth. I have installed the driver of the nRF8001, and I am able to pair both PC-UART. However, when I open the Master control Panel, I cannot find any Master emulator, the menu is empty. Master control panel version is 3.10.0.14.
Is there any way to connect a device with nRF8001 to a Windows 10 PC?
Thanks.


text:
Arduino Uno's RX and TX lights not blinking. Unable to upload sketches!
When arduino starts up, RX TX lights doesn't blink. Only the PIN 13 and Green light turns on. Pin 13 light blinks thrice before getting stable. RX TX lights are not blinking at all. I am not able to upload any sketches. The error I get is "Not in sync resp=0x00" or "Programmer not responding" or "Not in sync resp=0x95" or "Not in sync resp=0x69" and so on. A new error everytime. Most probably the error is with serial communication.
A brief history of what I have done
I have a Relay which is operated at 12V. But Arduino works at 5V logic. So I used a comparator (IC741) to improve the logic (By setting Vcc and -Vcc at 12 and 0 and the input pins connected to arduino). I also connected HC-05 bluetooth module to use the relay using my cellphone. You know what I was trying was home automation. Also Arduino was connected to 12V DC supply (I think this was my mistake). Everything was going right.
Suddenly IC741 started burning,maybe I shorted some pins when I was trying to measure the voltages using multimeter. I quickly removed it. Suddenly HC 05 started burning. I immediately removed all the connections. After some time I turned on Arduino again (This time using USB connected to laptop). I connected HC05. The bluetooth module heats up again. I thought the module is now gone. I turned to check Arduino and as I stated I am unable to upload any more sketches. Most probably the bluetooth module cause an error in serial communication. May be not.
So my question is
1. What's the real problem. Is my bluetooth module gone? Or is Arduino gone? If arduino is still fine, how can I get the serial to work back and enable me to upload sketches?
2. If Arduino is gone, most probably the microcontroller Atmega328 is still fine. How can I use it now without Arduino (I don't have any extra Arduino)?
Things I have already tried :

Loopback test : No echo back. Serial data can neither be sent nor received.
When I open the Serial window, Arduino doesn't resets as it it earlier.
RX TX Vin and 5V pin reads 4.99V. I hope they are fine.

say goodbye to the arduino.

I'm not going to write a speculative answer, but you've probably shorted 12V through to something and fried the comparator, the Bluetooth module, the ATMega328 serial pins if not more of it. If you remove the ATMega328 and connect the TX RX pins together on the Arduino, then send data through the serial monitor, do you see it coming back? If not, you've probably fried the serial pins of the ATMega32U4 as well.

Same here. I am pretty sure the damage was done when testing various things, never plugged a motor in AFAIK but it turns out capacitors on the wrong pin (eg D6) can sometimes send a spike back down into the USB chip and fry it.
The actual 328P works fine in my other Arduino.
Incidentally an out of spec 16MHz crystal can cause strange problems too.

Pin 13 light blinks thrice before getting stable.

It is supposed to do exactly that. See What happens when code is uploaded using the bootloader?

RX TX lights are not blinking at all.

That's not so good. See Have I bricked my Arduino Uno? Problems with uploading to board

If you are getting three blinks, most likely bootloader is fine but don't take it for granted. Also, post a schematic and picture of your original setup to get better answers in future.
Here is how you should start the debugging process:
1) Disconnect everything from Arduino especially from Tx Rx pins, and try to dump the blinky sketch. If it works, then arduino is good. If it doesn't work, follow this article to burn a fresh bootloader in your atmega. Check again. If not able to burn bootloader or code afterwards, get a new atmega IC for cheap and replace the damaged one.
2) Check the voltage requirements for HC-05 whether it's 3.3V or 5V. Make sure you are not giving it a higher voltage. If it starts to smoke as soon as you connect the GND VCC, then probably it has been damaged. Measure the resistance between GND and VCC of HC-05 before attaching. If it's less than 10-20 ohms, you already know that it's damaged.

Can you test the bluetooth module separately? i.e. just connect the power pins directly to the correct voltage source, and check if it overheats.  In this way you may be able to find the source of the short circuit.
If you shorted one or more of your arduino's I/O pins, you may have damaged your Atmega328 chip, since there's no protection between the chip and IO headers.  The other circuitry on the Arduino board is mostly power conditioning/regulation.  So I'm assuming that's not the problem.
Check if your 328 is getting the correct voltage at the VCC pin, to eliminate the power circuitry as the problem.

authors: Алексей Кузнецов


text:
Wifi rssi converting char[] to uint8_t
I am trying to get RSSI of a network without connecting to it directly but I get an error " error: cast from 'const char*' to 'uint8_t {aka unsigned char}' loses precision [-fpermissive]"
   char ssid[]="GreenNET";
    long rssi = 0;

    void updateRSSI(){
      rssi = WiFi.RSSI(ssid);
    }

I am following this: https://www.arduino.cc/en/Reference/WiFiRSSI except I am not passing password since it is not required WiFi.RSSI(wifiAccessPoint);

The argument passed to RSSI() must be an integer indicating the array index of the SSID of the WiFi network whose RSSI you want to get. To get that integer, you must first scan for networks.
char ssid[] = "greenNet";
byte num_ssids = 0;
long rssi = 0;

num_ssids = WiFi.scanNetworks();
for (byte net = 0; net < num_ssids; net++){
    rssi = WiFi.RSSI(net);
    Serial.print(WiFi.SSID(net)); Serial.print(": ");
    Serial.println(rssi);
}


text:
Safely powering a relay from same source as attiny/arduino?
My project involves using ATTINY to control a 5v relay (specifically JZC-11F and will be ground triggered) in an automotive setting.
I keep seeing the warnings of powering a relay from the same source as the ATTINY (or arduino), everything I can find says you need a completely separate source.
I'm still working on a 12~v to 5v power circuit that is safe from the issues that arise from being in an automotive setting (load dumps, noisy, reverse polarity protection..etc) but saying I have that figured out and I have a clean 5v source for power, do I have to duplicate that circuit just for the relay? or are there a ways of preventing the relay from eventually shorting out the ATTINY?
Plan B:
What if I scratch the whole 5v relay and set it up to trigger an external standard 12v automotive relay (this is probably more ideal)? Is the ATTINY capable of triggering a 12v relay via ground? if not what are the recommended ways of making this happen?
side note: I'm know code I don't know EE but I'm trying. The end goal is to combine everything onto a custom pcb, so any suggestions about the 12v-5 using an off the shelf car usb adapter or a premade board are unnecessary (seems to be the go-to answer on that subject). I have a separate post regarding that circuit so if at all possible please stick to the relay questions.

This question may be more appropriate for EE stack exchange. It will all depend on how beefy is your 5 V power source, on how much current the relay uses, and on your supply decoupling capacitors.

Why not use a solid state relay? Often they work on 5V/the output pins of a microcontroller.

@Paul: most solid state relays are for AC (triac-based) and won't work in automotive application. a MOSFET or MOSFET-based SSR designed for DC would work.

@EdgarBonet shooting for 5v 500mA, the relay I mentioned has a coil draw of 40mA and attiny is around 13mA

do I have to duplicate that circuit just for the relay?

No, not really, no.

Is the ATTINY capable of triggering a 12v relay via ground?

The ATTtiny is capable of triggering a transistor - the transistor is capable of triggering a 12V relay.
Unless your relay is incredibly high powered and the coil takes (and generates through back-EMF) massive amounts of current, there really is no problem running it alongside a small microcontroller. Just be sure you have the flyback diode, and maybe a damping capacitor as well to absorb noise.
TBH you're probably going to be getting more noise from contact spark than you are from the relay's coil.

Decided to drop the onboard relay and go with an external 12v relay w/ built in diode (301-1C-C-D1)


text:
Why is my Serial port not printing the right output?
am working with and Arduino nano and according to this, I can append strings to numbers by doing: stringThree =  stringOne + 123; but
when I do:
sensorValue = analogRead(A0);
String x1 = "{\"Volt\":"+sensorValue;
Serial.print(x1);

I get this unwanted output!

=gëÙrïË:_³ß»þ™¹Æ3+Ç#ÿ¼¿.Õ[Oû/g¯>ïÿ1þ†lú0

but doing this it works fine.
sensorValue = analogRead(A0);
String x1 = "{\"Volt\":";
x1 += sensorValue;
Serial.print(x1);

"Volt":646

why?

String concatenation uses dynamic allocation, which can be problematic on small-memory devices.  Anyhow, concatentation isn't needed for output -- see eg my answer to questions/33319 for Streaming alternative, and my answer to questions/16122 for another example.

I typically use Serial.println("Volt: " + (String)sensorValue);

In the first example you are adding an integer to the address of a string literal and then converting it to a String.
In the second example you are converting a string literal to a String and then appending an integer.
The key point here is string literal. The compiler just sees it as an address in flash memory. It's down to the functions you use with that address that define it as a string. So when you add an integer to it you are just adding an integer to the address, which of course changes the address. So then when you go to convert whatever is at that address to a String you end up with garbage.

Pretty nice explanation... it must be maybe some kind of pointer operation behind the scenes...

That is precisely what it is. In C there is no such thing as a "string", only a pointer to some memory location. It's only when you use that pointer that the contents are interpreted as a "string".


text:
Storing latitude and longitude floats as chars with specified precision
I am receiving lat and long data from a GPS and want to store these numbers in the middle of a sequence of chars.
E.g. lat = -23.123456
long = 135.123456
I am after something like "Your coordinates are -23.123456,135.123456" as an array of chars.
I have tried:
float latitude = -23.123456;
float longitude = 135.123456;

String one = "Your coordinates are ";
String two = ","
String message = one + latitude + two + longitude;

// Convert String to char array
int str_len = message.length() + 1;
char textmessage[str_len];
message.toCharArray(textmessage,str_len);

Serial.println(textmessage);

but the result is: Your coordinates are -023.12,0135.12
How can I correct this?
Thanks in advance!

Does your GPS actually give you floats?  Most output text on a serial port; if you do not need to do numeric operations on the values, perhaps you should just treat them as text all the way through.  Note that if you do use floats, their precision is limited, which may well be the cause of what you are seeing with your fake test data.

Are you sure about your result? I'm trying your code and I get "Your coordinates are -23.123456,135.123456". Just in case you didn't notice, you missing one ;

Regarding the limited precision of the float32 format: for numbers in the range [128, 256) (like your longitude), the unit in the last place is about 1.53e-5, which translates to a resolution of 1.7 m on the surface of the Earth. Assigning the longitude to a float can incur a rounding error as large as half an ulp, or about 85 cm.

Why not simply use the String member function c_str() to access the char array? message.c_str() https://www.arduino.cc/en/Reference/CStr

When formatting serial output is a concern, it's worthwhile to download and use the Streaming.h contributed library that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  If you don't have Streaming.h installed, you can get Streaming5.zip from arduiniana.org.
At present, Streaming.h doesn't support setw() and setfill(), which in ordinary C++ set a field width and a fill character.
However, it does support  four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and endl.
Thus, to print  “Your coordinates are -23.123456, 135.123456” one would write:
Serial << "Your coordinates are " << _FLOAT(latitude,6) << ", " << _FLOAT(longitude,6) << endl;

Note that unlike the String class, use of Streaming.h does not entail any dynamic memory management – everything it does happens at compile time – and it does not increase code size – it translates stream-style operations into ordinary .print() and .println() calls.  It should result in somewhat smaller, faster, and more-robust code, by avoidance of String.  Use of dynamic memory on small-memory embedded systems can be problematic, and this avoids those problems.

Edit 1a: As Chris Stratton points out, Arduino floats don't support 9-digit precision.  I think Arduino floating-point arithmetic is intended to comply with IEEE 754, which sets out standards to be used on modern computers that support floating-point arithmetic.
In the binary32 format used to implement IEEE 754 single-precision binary floating-point, significand precision is 24 bits.  That equates to about 7.22 decimal digits (ie, 24*log₁₀(2)), so for simple calculations, 7-digit accuracy is realistic, more than that is not.

[Part of] Edit 1b:  In the larger scheme of things perhaps there's no need to create and save a formatted string like that.  It is not useful for computing – the float values are better for that.  It is not needed for communication – another streaming write can be done.

Edit 2 [replaces most of 1b]: Streaming.h  doesn't build any strings, but just delivers the text of its <<-arguments character-by-character to a stream.  However, a PString class at arduiniana can build strings from stream inputs, as in the following example code.
#include <Streaming.h>
#include <PString.h>

char buffer[28];
PString pstr(buffer, sizeof(buffer));

void setup() {
  Serial.begin(115200);
  pstr.begin();     // Empty the buffer
}

void loop() {
  int first=50, second=100;
  pstr.begin();     // Empty the buffer
  pstr << 'X' << first << 'Y' << second << 'T';
  pstr += " hihi ";
  pstr << millis() << endl;
  Serial << pstr;
  delay(1000);
}

Here's what some of its output to Serial looks like:
X50Y100T hihi 263198
X50Y100T hihi 264199
X50Y100T hihi 265199
X50Y100T hihi 266201
X50Y100T hihi 267201
X50Y100T hihi 268201

What the sample of code does is first initialize a string buffer, then build part of a character string using streaming operator <<, then part of it using concatenation, then some more with <<, then print the string.  Note that the strings involved here are in fixed buffers, rather than dynamically allocated buffers like the String class uses.

It is possible you may do better than the code in the question, but you will not get the desired precision from an ATmega-based Arduino Uno's float.

Thanks! However I need to save this printed sequence as an array of chars to be used later in the code. Can this be done from the printed Serial <<... ?

@ChrisStratton, reflected in Edit 1a

@Anwar, please see Edit 1b

Although the streaming library is a nice syntax candy, you do not need it to specify the number of digits to print. You can also Serial.print(latitude, 6);.

@EdgarBonet, true.   But if one is doing a bunch of formatting (ie, the “When formatting serial output is a concern” case), Streaming.h helps keep the code compact and more clear than a long series of prints.  (My initial read of the question, possibly wrong, suggested formatting issues rather than getting-a-string issues.)

Thanks for all the input guys. However I am after a solution that does not read the string from the Serial window (as suggested in Edit 1b) as I will eventually use this module without being connected to a computer.

@Anwar, edit 2 explains how to build a string, using PString class.  In any case, 1a and 1b were about how to send data via Serial, with no suggestion about "read the string from the Serial window"


text:
Arduino stops loop randomly whenever a button is pressed
I'm having a problem with this Arduino code.
So whenever I press the "button" in port 11, which is supposed to either reset the burglar alarm or stop it, the whole program stops (the void loop() function stops). The wiring is most likely not the problem, because I've tested it on multiple occasions with different codes. The button, too, works perfectly well as a button with different codes.
In the Serial port, it keeps printing "78005", which it should before the button is pressed, until when I press the button, at which it randomly breaks off printing (resulting in 78, 780, 7, 7800, or 78005 as the last line printed).
Can anyone explain why the arduino will behave in this way?
Thank you so much.
int button = 11;
int receiver = 12;
int buzzer = 13;
int frequency = 1000; // frequency of buzzer

bool keepAlerting = false; // toggles Alarm regardless of detected charge
int receiverVal = LOW; // value from port 12
int buttonVal = LOW; // value from button
int oldButtonVal = LOW;

int setupTime = 5000; // time the user has to close the box after toggling alarm

bool alarmOn;
int buttonMode = 0;
const int resetButton = 1;
const int stopButton = 2;
int buttonModeDecider = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(buzzer, OUTPUT);
  pinMode(receiver, INPUT);
  pinMode(button, INPUT);
  Serial.begin(9600);

  noTone(buzzer);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("7");
  receiverVal = digitalRead(receiver);
  buttonVal = digitalRead(button);
  Serial.print("8");

  if(alarmOn == true){
    Serial.print("6");
    setAlarm();
  }

  Serial.print(buttonVal);
  Serial.print(oldButtonVal);

  if(buttonVal == HIGH && oldButtonVal == LOW){
    buttonModeDecider = 1 - buttonModeDecider;
    Serial.print("Toggled");

    if(buttonModeDecider == 1){
      buttonMode = resetButton;
      Serial.print("1");
    } else {
      buttonMode = stopButton;
      Serial.print("2");
    }

    switch(buttonMode) {
      case resetButton:
      {
        delay(setupTime);
        alarmOn = true;
        break;
        Serial.print("3");
      }
      case stopButton:
      {
        alarmOn = false;
        Serial.print("4");
      }
    }
  }
  Serial.println("5");
  oldButtonVal = buttonVal;
}

void setAlarm() {
  if(receiverVal == LOW || keepAlerting == true) {
    tone(buzzer, frequency);
    keepAlerting = true;
  }
}

How is the button wired?

You claim "the void loop() function stops", then you say "or 78005 as the last line printed". Can you really confirm this is the last line printed ONCE then nothing, or the last line reprinted forever, which would be much different than "the loop() stops" then.

For your inputs you use INPUT mode not INPUT_PULLUP, this means you added yourself a pullup or pulldown resistor "between" your button and the input pin, can you confirm this wiring? And then the opposite button side is connected to GND (if you use a pullup resistor) or +5V (if you use a pulldown resistor). A bad wiring here could make your program fail unexpectedly.

Add debouncing for your mechanical button. Your probably false detecting button press and release caused by bouncing. https://www.arduino.cc/en/Tutorial/Debounce

jfpoilpret: Yes, I can confirm that the last line printed is definitely the last line. It is not reprinted. Also, I can confirm the 10 ohm resister exists between my button and the input pin, and that the opposite button side is connected to GND. The wiring probably isn't a problem because if I use a different code with the same wiring to do other similar behaviors, it still works.

I have exactly the same problem. My friend just advised me to install the diode, as this apparently fixed his problem. We are working on the project from a couple of days and we wasted around 3 days, purely because of that. I have 20 lines of code, as everything was stopping working, as soon as we connect more devices. It like just stops working and it is broken and then suddenly become back to life. Yeah. We know what is going on. I may post the update about this diode once I install it on my rig.

Arduino stops loop randomly whenever a button is pressed

your button is shorting the supply?

A 10 Ohm resistor when switched to ground can cause the power supply to drop below the operating voltage of the Arduino. If you mean to have a pulldown resistor to ground use a 10K value instead.
Note that a 10 Ohm resistor across a 5V supply draws 0.5 Amps of current.


text:
What is the point of a adafruit data logger
In order to play an audio file, I was suggested to get an Adafruit data logger, yet right now I am stuck with the project and I realized that I'm not using the data logger to its full potential.
Yet I am unable to comprehend the purpose of a data logger ; all I'm using it for is to read SD Cards, and I can do that with a SD Card reader. I did read the whole documentation, data sheet, etc, and I can see that it has some cool functions, but my question is still, why data logger?
I know this  might be a stupid question, but I genuinely don't get what the data logger is supposed to be a huge help of. Please help me.

i don't know either, that doesn't make sense to me. free advice is worth just that sometimes...

Do you mean the Adafruit Datalogger Shield, or the Adafruit Feather M0 "Adalogger"

IMHO it have RTC+SD reader+libraries, so with minimal effort (and knowledge) anybody can alling those connectors, copy-paste some invocation and make magic like a real wizard. The Arduino underlaying principle. Or you can read datasheets, write your own code and make such PCB in kitchen yourself and not pay their premium prices (opens with knowledge, tools and experience). Or you could do it yourself, but it would cost you a week of work, so it is cheaper just buy it and fix it to your needs (opens with good job and money). So there are at least 2 groups, who buy it and so Adafruit sells it :)

why data logger?... maybe you can ask the guy/guys who suggested it to you? maybe they had some valid reasons? conceptually a data logger is there to log data.

Are you referring to this?

That is a shield that has an SD card interface (with appropriate level-shifting for the SD card) plus a real-time clock.
The rest is "prototyping" area for you to install your own devices.

In order to play an audio file, I was suggested to get an Adafruit data logger

I don't see how this helps play audio files, however you might read the audio file from the SD card. Then you need to send it to a DAC (digital-to-analog converter) to convert the digital information to analogue.
The Adafruit data logger is fine for recording data (for example, temperatures) but I don't see why someone would recommend it for playing audio files (apart from the SD card interface).

my question is still, why data logger?

Better ask the person that recommended it, eh?


text:
Sketch upload freezes during write
I'm trying to upload a huge sketch to my Uno R2. It's compiling just fine but it fails to upload at 94% of writing to flash...
The program is so large because of a big array of data in a separate .h file:
#include <avr/pgmspace.h>
const unsigned char PROGMEM data[] = {
  0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x80, 0x7f, 0x80, 0x7f, 0x80, (etc...)

A test sketch with just 12 bytes of data uploads fine, so the problem is either with the size or some weird bug triggered by some of the data.
Unless i'm missing something, this should technically work.
Command:
    /home/hatagashira/.arduino-1.6.5/hardware/tools/avr/bin/avrdude -C/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build8921209068074674980.tmp/program.cpp.hex:i

Output:
avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/hatagashira/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         Setting bit clk period        : 5.0
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 3.3
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as 0
avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as 0
avrdude: reading input file "/tmp/build8921209068074674980.tmp/program.cpp.hex"
avrdude: writing flash (30110 bytes):

Writing | ###############################################    | 94% 5.10savrdude: stk500_recv(): programmer is not responding

To make your question more answerable, first, make up a large example that succeeds in loading, and an example with a hundred more numbers that fails to load; second, edit the question to quote the compiler's size messages [eg, like "Sketch uses 20,112 bytes (65%) of program storage space. Maximum is 30,720 bytes."] for the failing and successful examples.

My two arduino nanos did flash and run the program correctly. I suspect a problem with the uno's serial communication but unwilling to troubleshoot further (i only have one uno). I decided to switch to the nano for further prototyping.


text:
Cast from long to int
How does arduino uno cast from long to int?
Does it truncate the bits? (Does it just delete the 16 most left bits?)

Yes, it just blindly chops off the upper 16 bits.  That means that the sign can change between the two.
For instance, 123456789 gets truncated to -13035 and -123456789 truncates to 13035.
To see that in more detail, look at the binary.  123456789 in binary is:
0000 0111 0101 1011 1100 1101 0001 0101

Truncate that at 16 bits and you get:
1100 1101 0001 0101

And of course the high (sign) bit is set, so the value is negative.


text:
H-Bridge L298N motor driver
I have 2 motors connected to a dual H-Bridge motor driver and the H-bridge connected to an arduino uno, It was working fine at first but now my motors are spinning very slow and the car bearly moves, I have changed the batteries  but still moves slow and with no power, please help

What motors? What driver? What batteries? Try to give a bit more detail.

I am also facing the same issue with my motor driver. Initially I ran the code and connected the L298N with arduino and it worked fine. At that time motors were running absolutely fine. But when I ran it sometimes later then the motors are not running. However the motors are getting power but I think thy are getting very less power from the Motor Driver. I directly ran motors from Arduino +5V pin and the motors were running fine. Is there something wrong with my L298N motor driver? One more thing I checked the power for all the pins for L298N motor Driver and all pins are working fine. Somebod

You can try to bisect the problem.
Remove the Arduino and drive the motors with wires: replace the input for the pwm signal with a +Vcc and you will get the same as if the Arduino was outputting a PWM with 100% duty cycle.
This should allow you to diagnose if there is a problem with the driver/motors.
If that shows no problem and the wheels spin as expected, then you have some issue (either sw or electrical with the Arduino).
But at least you can halve the complexity of the problem.

My motor has 2 wires and to run it through the H-bridge i use 3 wires, IN1,IN2 and ENB(PWM),so are u saying I should remove the H-bridge completely or leave the motor connected to the H-bridge just remove the wire connected to ENB and connect it to +Vcc?

(IN1,IN2) work like this: when they have different values, they make the motor rotate left or right., when they are the same value they erither let the motor free and unpowered or locked and powered. You can use wires to test the 4 combinations. the En/PWM can be set and left at high value (probably 5V in your case). So yes, I'd say you could drive manually IN1, IN2, EN. If that still shows problem, then you can consider breaking down that block.

I have EN connected to +Vcc and I have IN1 and IN2 connected to D5 and D6, one set at high and the other set at Low and nothing is happening

My point was that you do not need to connect IN1 and IN2 to the Arduino: just wire them to Vcc/GND and see if the motors move.

oh k, yeah the motor works and I have actually resolved that issue, now I need help with the ublox neo-6, I get 2812989, -2591969 and it keeps going up and down, how do i configure it to give me a fixed value, I am using TinyGPS library

This now seems like a separate question, I suggest you create a new one. You will get also more attention. I wouldn't know how  to solve this new problem you described.


text:
GPS coordinates
how do I compare coordinates I receive from the GPS module with the coordinates that I had hardcoded into the arduino, for example:
if (GPS reading <= hardcoded)
   movecarforward();
else
   movecarback();
the coordinates I get keep going up and down which makes it difficult for me to compare and excute the function below.Please help.....

You could check out the codes for this reverse geocaching project at https://learn.adafruit.com/reverse-geocache-engagement-box/software or the dog collar project at https://learn.adafruit.com/gps-dog-collar to get some help. For my GPS project I just wanted to display the distance and speed, so all I had to do was save the current location, subtract it from the previous location and add it to distanceTraveled. It'd be helpful if you could share your code here.


text:
How can I connect more sensors when my lcd is blocking pin access?
So, I have a lcd that takes up the whole board of an arduino mega. I want to connect a temperature sensor and make a really lame weather station, but the lcd screen is totally in the road. It's a shield so this is to be expected.
I've come up with wacky ideas, like soldering to the rear of the board but I think that's a bad idea. Surely there must be a better way? The lcd shield exposes no pins.

Which shield are you referring to?

Just solder some wires to the LCD shield. This way you won't "ruin" the main arduino board

What you need is a shield that can go between the Arduino and the LCD shield and break out whatever connections you like.
They are generally available as "screw terminal" shields, such as this one from iTead:

http://www.itead.cc/mega-proto-screw-shield.html

Like this? http://www.jaycar.com.au/Kits,-Science-%26-Learning/Electronic-Project-Kits/Computer-%26-Programming/Terminal-Shield-for-Arduino/p/XC4224

@LewisCianci Yep, except that's for the Uno not the Mega, so it would only give you access to a tiny proportion of the possible pins.

I see... I've had a look online briefly and the Mega 2560 compatible screw terminal shields have to be soldered together. Is there one that comes presoldered? EDIT: Sorry just realised that your link is for the Mega. My bad. EDIT UNO MAS: Why is it that these pre-made ones have to be soldered? I have a soldering iron but I don't really like working in such tiny spaces incase i solder two pins together or something :( but if i have to, I will

Uno shields are mostly all compatible with the Mega shields. So if the LCD is compatible with Uno and Mega then using a Uno proto shield it should not be a issue.

Sandwich an arduino protoshield in between and add the sensors to this board, or add some wires, so the sensor can be places "outside".


text:
Could I use metal buttons as a capacitive button for my arduino project?
Could I use something like this as a capacitive button for my arduino project?
http://www.banggood.com/10pcs-25mm-Vintage-Round-Metal-Buttons-Craft-Scrapbooking-Sewing-Suit-Shirt-Button-p-1011485.html
If I connect it into something like this... http://www.banggood.com/MPR121-Capacitive-Touch-Sensor-Module-For-Raspberry-Pi-Arduino-p-969002.html
Would that make that button a capacitive button? Or am I totally barking up the wrong tree here?
Thanks :)

What type of wires are you going to use? Wearable design? You might be able to do capacitive button detect directly without the module. Use an analog pin and a 1-10 M resistor, and some software. http://tuomasnylund.fi/drupal6/content/capacitive-touch-sensing-avr-and-single-adc-pin

I don't know. When I designed a capacitive button the IC I used required a metal plane with a dielectric, and you had to touch the dielectric (so you created a capacitor between the metal plane and your finger). Maybe there are other capacitive button controllers that require direct metal...

Yes, that would work.
The only thing to watch out for is that the buttons might be plastic with a thin layer of metal on top (Chemical vapor deposition).


text:
What could I use to vary the temperature of a Heating Pad?
Could I get something like this, a 12v silicone heating pad, and vary its temperature with an arduino somehow?
http://www.banggood.com/Waterproof-Silicone-Flexible-Heating-Pad-6060MM-DC-12V-10W-p-972464.html
My grand plan is to put temperature sensors on it and make it hit a certain temperature, and make it hotter/cooler to try and reach a target temperature.

Specifically, could I use something like this? http://www.banggood.com/MOSFET-Tube-Driver-Module-For-Arduino-SCM-ARM-Raspberry-Pi-p-938040.html

In principle, I don't see any problems. Your heating pad uses 12V and 10W, which means it would be consuming slightly less than one amp of current. The MOSFET you linked can go up to 5A (needing a heat sink with over 1A).
You could use PWM (there are 6 pins on a Uno that can do that) to provide pulse-width modulation to control the amount of output you give to the heater.
You would, of course, need to measure the heat of the device to work out when to adjust the PWM output. You might look up using a PID algorithm to adjust the PWM output depending on the sensed heat input.

References:

pid
pwm
mosfet
sensors

If you want to control the temperature very accurately, try connecting a shunt resistor (value: <0.1 ohm) in series with the heater. Use an op-amp to amplify the voltage difference on its two terminals and read with Arduino the resulting value. You can calculate with it the actual current and therefore the actual resistance of the heating pad.
The value changes with temperature, you can use the resistance value to measure the surface temperature of the heating pad.