Arduino Uno R1 I soldered resistor but I cannot DFU program atmega8u2 I have an Arduino R1 board (the very first one) and I managed to solder the resistor into Arduino's Atmega8u2 (I went to a specialist in order to do that). Then I reset atmega8u2 and by wiring the pins mentioned in: https://www.arduino.cc/en/Hacking/DFUProgramming8U2
I can confirm it via this message over my GNU/Linux machine by running dmesg:
[ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
[ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
[ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 1544.808356] usb 1-6: Product: Arduino Uno DFU

I also to confirm that I run lsusb and I got the following result:
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 002: ID 248a:8367
Bus 001 Device 058: ID 03eb:2ff7 Atmel Corp.
Bus 001 Device 003: ID 058f:6362 Alcor Micro Corp. Flash Card Reader/Writer
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Further indicating to me that arduino is in DFU mode over my ubuntu 16.04 machine. Also I further verify via dfu-util -l command:
Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

Found DFU: [03eb:2ff7] ver=0000, devnum=63, cfg=1, intf=0, alt=0, name="UNKNOWN", serial="UNKNOWN"

The I try to run:
sudo dfu-programmer atmega8u2 erase
But for some reason I get the following error:
dfu-programmer: no device present.
Do you know why I get this error and how I can fix it?
Edit 1
I installed the latest version of dfu-programmer and compiled from source via https://sourceforge.net/projects/dfu-programmer/files/dfu-programmer/0.7.2/ but still I get the error. I also tried to compile it with libusb-1.0.0
Edit2
I also tried this version with libusb-1.0.0 but still the same error occurs.
Edit 3
As many suggest I tried to do multiple times but still I get this error.
Edit 4
I also used dfu-util and I try to insert the data into the atmega8u2 via:
 sudo dfu-util -d 03eb:2ff7 -D ./Arduino-usbserial-uno.hex -R

But I get the error:
dfu-util 0.8

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2014 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to dfu-util@lists.gnumonks.org

dfu-util: Invalid DFU suffix signature
dfu-util: A valid DFU suffix will be required in a future dfu-util release!!!
Opening DFU capable USB device...
ID 03eb:2ff7
Run-time device DFU version 0100
Claiming USB DFU Interface...
Setting Alternate Setting #0 ...
Determining device status: state = dfuIDLE, status = 0
dfuIDLE, continuing
DFU mode device DFU version 0100
Device returned transfer size 3072
Copying data from PC to DFU device
Download    [                         ]   0%            0 bytesdfu-util: Error during download
dfu-util: can't detach
Resetting USB to switch back to runtime mode

According to https://gebloggendings.wordpress.com/category/elektronik/arduino/ it is sometimes not to assume that the atmega8u2 is always the correct value in my case was the at90usb82 resulting into using the following command sequence:

sudo dfu-programmer at90usb82 erase
# Flashing the arduino provided .hex
sudo dfu-programmer at90usb82 /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/arduino-usbserial/Arduino-usbserial-uno.hex
# reset the board
sudo dfu-programmer at90usb82 reset

Further information you can find into:

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


How to wire an analog IR sensor for digital input? How do you wire a phototransistor so that it outputs a clean digital signal in response to certain light levels?

I've wired a QRD1114 to an Arduino analog pin to detect a white or black surface. However, I want to use this sensor to detect fast movement of a black/white color strip, and since analogRead() can take up to 100µs and I'd rather use the ADC pin for other sensors, I want to rewire this so I can read the same signal with digitalRead().

In order to do this, the sensor needs to output less than 2.3V for white and more than 2.5V for black. I'm pretty close, but I'm having trouble with black. For white, the voltage drops to 0.7V, so that reads perfectly, but black still reflects a lot of IR, so it typically reads 2.3V, which still translates as a LOW value.

My sensor's circuit is a pretty basic voltage divider:

R1 is the Arduino's built-in 20k pullup. R2 is a variable resistor I've tried using to "shift" the voltage level up for the black case. Unfortunately, I've found this very difficult to calibrate. The larger I make R2, the higher the black-case voltage gets...but so does the white-case voltage. By the time I make R2 large enough so that black registers as HIGH, white also registers as high. Through trial and error, I found 25.7k ohms is the sweet spot, but the difference in voltage between the two is about 0.5V, which makes me nervous about getting false readings.

I've measured the phototransistor's resistance in each case, and for black it reads as 12.5k ohms while for white it reads as 9.7k ohms.

Given my 25.7k calibration resistance, the voltage divider should output for black:

Vout = Vin * R2/(R1 + R2)

5 * (12500+25700)/(20000 + 12500+25700) = 3.2V

and for white:

5 * (9700+25700)/(20000 + 9700+25700) = 3.1V

However, for black, my meter reads 2.3V for black and 2.0V for white.

Why do my meter measurements not match the voltage divider formula? Am I wiring this voltage divider correctly?

What can I do to get a cleaner digital output without complicating the circuit too much?

Near the bottom of:

https://learn.sparkfun.com/tutorials/qrd1114-optical-detector-hookup-guide

shows a graph of the voltage for a white surface and a black surface. If I understand your question correctly, I think you can get your desired results by controlling the distance between the sensor and the surface. For example, at 0.5mm white reads about 0.1V while black reads about 3.2V

A 330Ω current-limiting resistor and a 10kΩ pull-up resistor were used in their circuit.

Hope this helps.


Need a simple accelerometer visualization example! I'm doing a project using the ADXL335 accelerometer from SparkFun. The actual project I'm using P5 and it's working great. I'm running workshops in parallel and want to demo the chip in real-time but am currently out of time to build something from scratch. I'm desperate for a simple processing (or something else) sketch that takes my x, y, z values being printed to the serial port from Arduino and visualizes them in some way. Can anyone point me to anything that won't need a lot of coding time and effort just now?

Thank you!
Claudia

After some quick searching I found an Instructable which uses your same sensor and plots the data thanks to a Python script.

You'll need to install Python if you want to replicate this project, but any programming language with a drawing library will work.


Sweeping servo 90 degrees #include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

I have found this code that makes servo go 180 and back, but when I switch 180 degrees with 90, which is what I need, my servo doesn't do that (I tried the code in Arduino simulator).

Do I have to change something elese in the code (like delay time) so it whould go 90 degrees up and then 90 down?

Here is the link of circuit:

https://circuits.io/circuits/3597808-servo-90-degrees

No you don't have to change any time delay in order to get it rotating by 90 degrees, delay would just change the speed of rotation of the servo. The simulator you are using is at fault here as the sketch with 180 changed to 90 works flawlessly.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos < 90; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 90; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

MAKE SURE THAT YOU CHANGE BOTH OF THE 180'S TO 90.


Maximum signal frequency obtained at the gpios of arduino mega 2560 Is it possible to obtain the rectangular pulse signals of freuency 10 MHz simultaneously at the GPIOs of arduino mega 2560?

The maximum fundamental frequency you can generate is fcpu/2 - or 8MHz with the default 16MHz resonator / crystal.

What shape the actual signal is, though, is very much dependant on the load on the IO pin. The IO pin has a specific drive strength which will provide limited current into a load. Any capacitance or inductance within that load causes a change in the slew rate (also known as the rise time or fall time) of the IO pin, which affects the shape of the signal by limiting the highest harmonic frequencies you observe.  At the worst case scenario, you get an almost sine wave (only the fundamental frequency gets through). In general though you get more of a rounded-off square wave:

You can improve that slew rate by adding a buffer with a higher drive strength to the output (assuming your buffer has a high enough bandwidth).  However, the IO pin itself will always have a certain amount of curvature to the signal due to its own internal capacitances.

For generating higher frequencies you are better off using a chip that is designed to operate at higher frequencies.


Automatic/manual door lock with servo I'm building an automatic door lock, which is moved by a servo ( this one ). However, I want to still make it possible to open the lock manually, but it's not possible if the servo is attached to the lock mechanism.

Do you have ideas on how to go around this problem?

Here's a diagram of the lock mechanism

So it's actually the worm gear that is causing your problem, since that can't be reverse driven by the cogs.

The simplest option, I think, would be to have the middle cog normally separated from the worm gear and only re-engage it when you need to drive the mechanism with the servo.  You could maybe use a second servo to move it into the right place, or maybe a solenoid, or something along those lines. Have it slide along a short track or slot with a spring to ensure it disengages when the solenoid is released.


Comparison of a bit vs. setting a bit Simple question really, I just want to be sure that I understand it correctly. I understand this isn't necessarily Arduino specific.

With regards to the ATmega2560 I'm doing 3 back-to-back A/D conversions - one immediately after the previous finishes. I'm accomplishing this by calling a Single Conversion each time.

I stumbled across this useful code to wait for the conversion to finish:

while(ADCSRA & (1<<ADSC))

I understand that it is waiting for the conversion to finish and that when this is done the ADSC will be set to 0. (Conversely, I could wait for ADIF to be set to 1.) I'm not as clear on how exactly this line is interpreted.

Normally when I see something along the lines of (1<<ADSC) it means write a 1 to the ADSC bit.

But, in this instance, that isn't the case.

Why not just write:

while(ADSC);

You misunderstand the meaning of:

1 << ADSC

That actually means Bit-shift 1 left by the number of bits specified by the value ADSC.

ADSC in this case is 6:

#define ADSC    6

So if you did:

while(ADSC);

you would actually be doing:

while(6);

Which of course will never end, since 6 is not 0, so is true.

Instead you shift 1 left 6 times, which in binary would be:

00000001
    << 6
01000000

That, of course, is 64, or 0x40 in hexadecimal.  That is then ANDed with the value of the ADCSRA register to return the value of one single bit within that register.  It's then the result of that AND that you control the while with.  So it ends up as:

while(ADCSRA & 0x40);

Which will either equate to:

while(0x40);

if the 7th bit is set, or if it's not set:

while(0x00);

And since 0x00 is 0 it will equate to false when the bit isn't set and the while will finish.


How does this Motor Circuit not ruin the Microcontroller I came across this instructable about using no external hardware but two pwm pins to control a motor in both directions. Usually you would use an H bridge. However, ever since I have had my Arduino I have heard that you are not supposed to connect a pin to another pin. So how does this circuit works. It looks like he sends a signal from one pin and in my experience it would fry the board. So basically, my question is this circuit ok with an Arduino Nano and if so how does it work? Below is a picture of the setup he gave:

This is a bad idea, but not because two pins seem to be connected directly. They're not; there is a load (the motor) between the pins, and that motor will take care of different levels between the pins. High and low will make the motor turn one way, low and high the other way, and the same level on both pins will stop the motor.

Why is this bad? An I/O pin can only supply a limited current, and even for a small motor that will peak rather high. If you run the motor for some time this way you will damage the I/O ports. An H-bridge, like you mention, is the solution.
Note that electric motors cause a lot of noise in the power supply, which may cause the microcontroller to reset all the time, so that your program doesn't work. (The motor may seem to start/stop all the time.) You need to decouple the power supply with capacitors.


3.3V from 5.0v outlet I am working with an Adafruit Feather 32u4 FONA board. I want to connect a GPS module I have worked with before (3.3V required) but am not having much luck. I have studied the pinout of the board and have tried the 3.3V pin but it is far too erratic in nature and cannot sufficiently power the module. There is a pin called USB which supplies 5.0V from the pin if a micro USB cable is connected. I have used an LM317 and a potentiometer to make a voltage regulator circuit to convert the 5.0V from the USB pin to the 3.3V I need for the GPS module. This works, as I have measured 3.3V successfully using a multimeter.

The problem is that when I connect the VCC and GND pins of the GPS module to the 3.3V regulated output, the module still doesn't get any power. I measured a significant drop to around 0.89V across GND and VCC after I connect the module. What could be causing this strange behavior?

The bottom left rail is what I am trying to use to power the GPS module, before I connect it I get 3.3V as mentioned earlier, which is the required level.

According to the datasheet the LM317 has a minimum Vin to Vout of 3v so you'd only be able to get 2v out of it if you put 5v in.  I'd recommend using either an AMS1117 3.3 or one of the cheap modules based on that chip that has an LED and capacitors on board. They definitely deliver 3.3v from 5v in.


How to program an Arduino Uno Pro with a makefile? I'm using Arduino Makefile to compile sketches for Uno and Mega boards. I'm now trying to compile a sketch for an Arduino Uno Pro, which is an Uno with a replaced chip to give it features more like a Mega.

When writing a makefile to compile for this board, which BOARD_TAG should I use? I don't see this board listed in the official Arduino or Arduino Makefile docs.

After you edit your boards.txt file to incorporate the Arduino Uno Pro section from near the end of that Arduino Uno Pro webpage at hobbytronics.co.uk that you referenced, the board tag list produced by make show_boards will include the following line:

uno_pro       Arduino Uno*Pro

indicating the tag should be uno_pro.


How to read voltage using ADS1115 I'm very new to this. I found this tutorial.

But it don't explain how to read voltages higher than Arduino 5V. I have connected a 100K ohm resistor to positive and 10K ohm to negative of my 24V power supply.

I need some guidance for writing the code for this specific ADC, please.

As KIIV mentioned you need to do the math:

Use this online voltage divider calculator to calculate your maximum input.

Keep in mind you shouldn't exceed Arduino 5V.
Use a multimeter to measure the resistors actual resistance.
Do the math for your example assuming R1 is exactly 100K and R2 10K you have to multiple the voltage by 11.
remember any error is going to multiple by 11 too, so make sure the first reading is accurate/stable.

ADS1115 is actually 15bit which will give you resolution of 32768, with default PGA setting you get:
6.144 / 32768 = 0.0001875V per bit.

Voltage = (your ADC reading) * 0.0001875V;
Voltage = Voltage * 11;

Take a look at This question/answer to see how I did reduced Arduino ADC noise, some steps can be done for ADS1115 as well.


How to connect an Output to a Pullup Input of another arduino :tldr; Could problems occur if one connects a HIGH Output of one arduino to a PULLUP_INPUT of another while using differed power sources?
Hi I'm building some devices for a LARP Dungeon (think Escape room).
For that we have interfaces, riddles and switches(triggers).
Interfaces provide access to sound/light/DMX sytems for riddles.
Riddles check conditions and send state information to the interfaces.
To keep things simple, states are boolean (like riddle is solved, a critical mistake has been made,..)
I would like to use PULLUP_INPUTs on the receiving end so I can use simple switches to GND as controls. In some cases a switch might be connected directly to an interface. Mostly there is a riddle in-between. In those cases an OUTPUT of the riddle's Arduino will be connected to the PULLUP_INPUT of the Interface's Arduino. There will be multiple riddle Arduinos connected to one or even multiple Interfaces.
Due to cable length, differed power sources etc. the potential to GND of the involved Arduinos might be differed. So I assume this difference will flow over the pullup resistor of the interfaces into their 5V. The internal PULLUP is ~20kOhms so current should not be a problem but can the voltage, which might be a little higher than the one of the input, cause problems?
Or would it be better to set the Output of a riddle Arduino to INPUT while the signal line should be HIGH so it gets a high impedance? Switching between: OUTPUT:LOW while active and INPUT while inactive.

Connecting any signal that is within the voltage range of the receiving Arduino is safe. So if you use Arduino UNOs or similar with a 5V operating level, you can connect any signal between 0 and 5V to an input. It does not matter whether the input is in pull-up-mode or not. So connecting an output to an input of another Arduino (or even of the same Arduino) is safe. In addition to the signal values, you do need to connect the ground of both Arduinos.
The only thing you must not do is connect two outputs together (because if one of them is high and the other is low, you have a shortcut that will potentially fry one or both of the boards). And you would need to be careful if you used different types of Arduinos, like a Uno and a Due, because they run at different voltage levels.


Floating pins: digitalRead returns always high or always low I was trying to see whether my board operates as expected with random readings on floating pins. Oddly it does not. The following code produces all HIGH readings:

#define PIN_MISO 12

void setup() {
  pinMode(PIN_MISO, INPUT);
  Serial.begin(9600);
}

void loop() {
  uint16_t data = 0;
  Serial.print("MISO digitalRead: ");
  data = digitalRead(PIN_MISO);
  Serial.println(data, BIN);
  delay(300);
}

MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1

I tried grounding pin 12 and after a few seconds the readings all came back LOW as expected. However leaving it floating produces all HIGH instead of random readings.

I tried the same program for pins 3 and then A3 with more weird output: all LOW.

What am I missing here?

Floating means it would generate any value. This could be a result of innumerable factors and it is HIGH in this case! you cannot expect anything other than a HIGH or LOW.

Think of it this way-
It's fluctuating in a range of about 900-1000 but the range is still very close to 1023 hence it results in a HIGH.

Some other time it may be near the lower values then it would show LOW.


How do I erase internal EEPROM on a Arduino Pro Mini I'm working on Arduino pro mini.
and I store some data in internal EEPROM.

So, I want to erase certain data from 0x00 to 0x28 address in EEPROM.

void loop()
{
 ...
 ...
 if(erase_eeprom_flag==1)
 {
   addr_uu=0;
          erase_eeprom_flag=0;
          for(kk=0;kk<28;kk++)
          {
              EEPROM.update(addr_uu,0);

              addr_uu=addr_uu+1;

          }
          Serial.println("OK");
          Serial.println(addr_uu,DEC);
          addr_uu=0;
      }
  }

But I got a data like(28 times '0' and other data 'xxx') "0000000000000000000000000000xxxxxxxxxxxx".

ex : 20170519    --->   expected data: 00000519
                        (inappropriate data: 000020170519)

So, here actually push "0" / add at begin operation happen but I want to remove data from those address.

Please tell which Arduino function help me for solving my issue.

You are clearing 28 decimal bytes, but your address range is 28 hex bytes, or 40 bytes of data.  Hence, the last 12 characters are untouched.


USB and UART simultaneous power to Arduino? I am connecting an Arduino Mega (Crius) to a Intel Embedded processor (Minnowboard) via the following to Peripherals:

Minnowboard USB            -> Arduino      (to flash the micro-controller)
Minnowbaord Highspeed UART -> Arduino UART (to communicate)

Now both the peripherals are supplying +5V Vcc to the Arduino from the Minnowbaord but via different ports. Both the channels shall always remain connected.

Is it safe to power +5V from different ports to the Arduino (because i am technically bypassing all the voltage regulators available on board) ?

Will this cause any problems for the Arduino in regards to difference in voltage levels?

That's perfectly fine.  As it's the same 5V source the voltage should be the same and it'll just combine them together as if you had 2 wires in parallel.  However, if there are things like diodes in the path of one connection that causes the voltage to be slightly lower then the increased voltage imposed on the lower voltage side would reverse bias those diodes and end up cutting off that one source, so only one would be used.

So no, it's nothing to concern yourself over.


What is it you hope to achieve by "opening" the hex file or "converting it to binary"?

A hex file is a compiled sketch. It is intended to be installed into the Arduino Uno using avrdude.


RGB LED strip inverted PWM This bug/stupidity-of-myself/problem is killing me:
I'm have created an RGB strip controller that cycles through the additive-rgb-color spectrum while turning a potentiometer.

I have a pot hooked up to my Arduino Nano v3 (from AZ-Delivery, not official Arduino). Then I have an RGB amplifier hooked up to the Arduino with each phase (R, G, B, V+) and to an external power supply (12V by 2A max).

I shortened my program and removed all the value-to-colour-conversion because that has nothing to do with the problem:

void loop() {
    ColorVal = analogRead(pinPot); //read value of color poti
    ColorByte = map(ColorVal, 0, 1023, 0, 255); //Scales 0-1023 to 0-255

    // potvalue to color conversion
    // ...

    // write via PWM to LED
    analogWrite(pinR, R);
    analogWrite(pinG, G);
    analogWrite(pinB, B);
}

My problem: Theoretically you would expect the system to show white when all variables (R, G and B) are set to 255. However, it behaves the other way around. When all values are set to 255 it's off and vice versa. Another example: When R = 255 and G = 0 and B = 0 Green and Blue are lighting and Red is off.

I thought this has to do with polarity or something but I cannot seem to find it out.

The RGB LED strip has a common anode (V+). When you put 12 V on R, G or B, the LEDs have 12 V on both sides, so there is no voltage across it and no current.

And if you put 0 V, they have 12 V across it and light up.

To fix it, just invert the PWM value in your code:

analogWrite(255-pinR, R);
analogWrite(255-pinG, G);
analogWrite(255-pinB, B);


Print 2 numbers stored in 24-bits in decimal format An implementation function from the nice little Wiegand library YetAnotherArduinoWiegandLibrary prints a hexadecimal representation of a facility # & card # (8-bit facility #, 16-bit card #) — 24 bits of a 26-bit stream that comes across the wire.

Example encoded 24-bit number: 7111097 (decimal). Hex equivalent: 6C81B9. The 6C portion is the facility # (decimal: 108). 81B9 is card # (decimal 33209).

This function from the library's example usage serial prints the hexadecimal format of the number:

void receivedData(uint8_t* data, uint8_t bits, const char* message) {
    Serial.print(message);
    Serial.print(bits);
    Serial.print("bits / ");
    //Print value in HEX
    uint8_t bytes = (bits+7)/8;
    for (int i=0; i<bytes; i++) {
        Serial.print(data[i] >> 4, 16);  //1st, 3rd, 5th hex digit
        Serial.print(data[i] & 0xF, 16); //2nd, 4th, 6th hex digit
    }
    Serial.println();
}

What I've tried to do unsuccessfully so far is to loop over the bits to also serial print the two decimal formatted numbers (facility:card) in the final output form:  108:33209

Your code loops from the high order byte to the low order byte, printing each byte as 2 hex digits.

If you want instead to print the first byte as a decimal value, and then the remaining bytes as another decimal value, then do this:

Print byte 0 in base 10:

    Serial.print(data[0]);  //first byte
    Serial.print(":");

Then loop through the remaining bytes, building a result as a decimal value, and print that:

unsigned long total = 0;
for (int i=1; i<bytes; i++) //Skip the first byte
{
    total = total << 8;  //Shift the previous total by 8 bits.
                         //(The same as multiplying by 256, but faster)
    total += data[i];    //Add in the new value
}
Serial.println(total);

The sample code you posted is written to handle a variable number of bytes. The code above does the same thing with decimal results. It's much simpler if you know you will always have 3 bytes or 4 bytes:

For 3 bytes:

    Serial.print(data[0]);  //first byte
    Serial.print(":");
    long total = long(data[1])*256 + data[2]);
    Serial.println(long(total);


why arduino can not write to server? i write a code for Arduino + SIM800 for connecting to server.
but it don't work!

SerialGsm.println("AT+CIPSEND=63\r\n");
delay( 1000 );
receive_message();
SerialGsm.print( "GET http://sasasas.ir.ir/hadi/signal.php?value=10" );
delay( 10000 );
receive_message();

all thing is true but "GET" can not retrun "OK".
it is arduino response:

AT

OK

Call Ready

SMS Ready
AT+CSTT="mtnirancell"

OK
AT+CIICR

OK
AT+CIFSR

100.65.157.141
AT+CIPSTART="TCP","sasasas.ir",80

OK

CONNECT OK
AT+CIPSEND=63

  GET http://sasasas.ir/hadi/signal.php?value=10

"get" dont have response.what is wrong in this code?

Firstly you only have half of the first line of a GET request. Secondly the half you do have is badly formatted.

A GET request does NOT look like this:

GET http://jalambadani.ir/hadi/signal.php?value=10

A GET request DOES look like this:

GET /hadi/signal.php?value=10 HTTP/1.1
Host: jalambadani.ir
Connection: close
[extra blank line]

If you don't send the correct data you can't expect to get any response back.  You should learn the basics of what you are trying to do instead of just throwing random text a a web server.

Here is a full transcript of a GET request to your URL:

$ telnet jalambadani.ir 80
Trying 185.211.56.148...
Connected to jalambadani.ir.
Escape character is '^]'.
GET /hadi/signal.php?value=10 HTTP/1.1
Host: jalambadani.ir
Connection: close

HTTP/1.1 200 OK
Date: Tue, 25 Jun 2019 22:47:07 GMT
Server: Apache/2
X-Powered-By: PHP/5.6.35
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: User-Agent
Content-Length: 31
Content-Type: text/html; charset=UTF-8

New record created successfullyConnection closed by foreign host.

In code that would be:

SerialGsm.print("AT+CIPSEND=83\r\n");
delay(1000); // I hate that. Look for a proper OK instead.
SerialGsm.print("GET /hadi/signal.php?value=15 HTTP/1.1\r\n");
SerialGsm.print("Host: jalambadani.ir\r\n");
SerialGsm.print("Connection: close\r\n");
SerialGsm.print("\r\n);


DHT 11 sensors and i2c LCD to Wemos Wifi not Working Its my first time make arduino project. I make wemos d1  project using DHT11 temperature sensor and LCD 20x4 with i2c. The temperature data will display in LCD and sending to the bot telegram. For sending to the bot telegram it works, but why the data cannot display to the LCD? When I tried common charachter like "Hello World!" in the LCD it works. Can you help me? What should I do? Thanks before.

#include "DHT.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE);
#define DHTPIN D14
#define DHTTYPE DHT11

byte degree[8] = {
  0b00110,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};

DHT dht(D14, DHT11);

void setup() {
  lcd.createChar(0, degree);
  Serial.begin(115200);
  Serial.println("DHT11 test!");
  lcd.begin (20, 4);
  dht.begin();
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  lcd.setCursor(0, 0);
  lcd.print("Humi : ");
  lcd.print(h);
  lcd.print(" %");

  lcd.setCursor(0, 1);
  lcd.print("Temp : ");
  lcd.print(t);
  lcd.print(" C");
}

Constant D14 is for Wemos D1 and other esp8266 dev boards mapped in arduino core to esp8266 io pin 4. Pin 4 is used as I2C SDA pin. The LCD uses I2C so pin 4 (D14) can't be used for the sensor.

from pins_arduino.h for Wemos D1 R1:

#define PIN_WIRE_SDA (4)
#define PIN_WIRE_SCL (5)

static const uint8_t D14  = 4;
static const uint8_t D15  = 5;

The origin of this confusing esp8266 io pin to Dx constants mapping is the big Wemos D1. There are esp8266 pins mapped to standard Uno pinout.


Arduino mega board 5v pin does not gives 5v when 7.5v is applied through external source I gave 7.5v to the arduino mega board through battery. 5v pin in the board gives me the same voltage as input. Earlier it was working fine now it is giving problem.Please let me know the solution as soon as possible.

Thanks and regards,
Thippeswamy

If you apply 7.5V to the power barrel jack and the 5V pin is 7.5V then your Arduino board is broken. Don't connect it to a computer. Don't use it anymore.


Air quality sensor reading meaning So I got this air quality sensor running, and it's outputting some numbers.
I've read some tutorial online and it looks like the smaller the number the better the air quality.
But I don't understand what is the meaning of those number. Like what is the unit of measurement? For example, the temperature sensor gives you numbers in Celcius degree.

http://wiki.seeed.cc/Grove-Air_Quality_Sensor_v1.3/

One of those MQ gas sensors ? They are electrochemical sensors. They can be calibrated more or less with a known concentration of a certain gas. But since the are often sensitive to a number of gasses, you do not know the concentration of that specific gas that was used for calibration.

A number that is going up and down is what you have. You can make a graph with it to show the value for each hour or each day.

The MQ gas sensors have a "preheat" or "burn-in" time. It is often 24 hours. Keep the sensor on for 24 hours to get more stable output values.

A temperature sensor is completely different, it contains electronics inside and has been calibrated at the factory. The MQ gas sensors are just a few wires, a heater and some chemicals.

[ADDED]
That is a module with the MP503 gas sensor. It just like the MQ sensors a electrochemical gas sensor. According to the datasheet it is sensitive for alcohol and smoke and the "preheat" or "burn-in" is called "aging time" and can be up to one week! The module has a amplifier.

The detection of gasses is according to a certain curve. To calculate the concentration of gasses a calculation is needed (and a calibrated sensor). I don't see that calculation in the supplied library. So all you have is numbers that change according to the air quality. That's all. And that is normal for these sensors.

Read the information and pdf files on that seeed page about this Grove module. It clearly says that you can't measure the concentration of gas (not "quantitatively"), you can only tell if the air quality gets better or worse (qualitative).


analogReference(INTERNAL) configuration I need some help because I did not understand the configuration analogReference(INTERNAL).
I would measure the intensity of a Laser beam passing through a filter. This is the circuit I would implement, using the 3.3 V power supply:

In order to rise up the resolution of the system, I would use the 1.1 V power supply (Arduino Uno) to feed the sensor, keeping the Laser power supply at 5 V. In the analogReference(EXTERNAL) configuration shown in the schematic, the sensor is powered by the 3V3 pin, which is connected to the AREF pin. How should I change the circuit in analogReference(INTERNAL) configuration?

Changing the analog reference does not change the resolution.  All it does is change the measurement range. It compresses the existing resolution into a smaller voltage range.

If you then compress the voltage range of your signal in the same way to fit into the now compressed analog reference voltage range (for example by reducing the supply voltage to 1.1V) you end up achieving absolutely nothing.

The only time you would use the 1.1V internal reference is if your incoming signal is already between 0V and 1.1V and you would otherwise be wasting the resolution above the highest voltage the sensor gives out.


Reading data from airspeed v3 eagle tree I am trying to get values from this sensor Airspeed v3 from eagle tree but it seems my I2C is not working properly.

I bought a module in third party mode and followed these instructions from the manufacturer website.

I went to rcgroups forum and discovered the right values for the bits mentioned in the documentation about WRITE and READ.

I started the development of a code but I cannot get the values from the sensor. It is supposed to send me a 2 byte-formatted value indicating the airspeed measured. But surprisingly when I call this method Wire.requestFrom(AIRSPEED_ADDRESS, 2) it returns 0, so someway the communication is not working. I have used I2C before for ADXL345 sensor and it works perfectly.

The results from these lines

Serial.println(data[0]);
Serial.println(data[1]);

are just -1 indicating that no data is available to display.

Does anybody know how to get this working? Am I missing something?

This is my code right now.

#include <Wire.h>

#define AIRSPEED_ADDRESS  0xEA
#define WRITE_BIT         0x00
#define READ_BIT          0x01

void setup() {
  // join I2C bus (I2Cdev library doesn't do this automatically)
  Wire.begin();
  Serial.begin(9600);
  Serial.println("Program started");
}

void loop() {
  byte data[2] = {0};
  int i = 0;
  int16_t velocidade = 0;

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  if (!Wire.write(WRITE_BIT)) {
    Serial.println("error sending write_bit");
  }
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  if (!Wire.write(0x07)) {
    Serial.println("error sending 0x07");
  }
  Wire.endTransmission(false);

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  if (!Wire.write(READ_BIT)) {
    Serial.println("error sending read_bit");
  }
  else {
    //Serial.println("ok sending read_bit");
  }
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Serial.print("bytes read from slave: ");
  Serial.println(  Wire.requestFrom(AIRSPEED_ADDRESS, 2) );
  data[0] = Wire.read();
  data[1] = Wire.read();
  Wire.endTransmission();

  velocidade = data[1] | (data[0] << 8);
  Serial.println(data[0]);
  Serial.println(data[1]);
  Serial.println(" ");

}

I found the I2C address on my Eagletree Airspeed V3 sensor to be 0x75 NOT 0xEA.

the following code adapted from first sample above works on my Nano:

/*
 * note that timming is critical - see delay (5)
 * and bps set to 115200
 * works ok, but clean up 5-19-2019 jaf
 */

#include <Wire.h>

#define AIRSPEED_ADDRESS  0x75
#define WRITE_BIT         0x00
#define READ_BIT          0x01

void setup() {
  Wire.begin();
  Serial.begin(115200);
  Serial.println("Program started");
}

void loop() {
  byte data[2] = {0};
  int i = 0;

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(WRITE_BIT);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(0x07);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.write(READ_BIT);
  Wire.endTransmission();

  Wire.beginTransmission(AIRSPEED_ADDRESS);
  Wire.requestFrom(AIRSPEED_ADDRESS, 2);
  data[0] = Wire.read();
  Wire.endTransmission();

  Serial.println(data[0]);
  delay(5);
}


Nodemcu v3 - Power supply via VU pin? I want to control two hitec hs55 micro servos via a Nodemcu v3. These need at least 4.8 V power supply acc to data sheet.
Specs:
Hs-55 micro servo:
Voltage range: 4.8-6 V
Current Drain - no-load (4.8V): 150 mA
Pulse Amplitude: 3-5V
NodeMCU (v3):
From what I found it seems like it can "reliably supply 600 mA".
3.3V pins (standard)
5 V (pin VU), Directly connected from the USB (?)
From what I understand it is generally a good idea to supply power to servos separately, otherwise the board can be damaged. Is this also the case here or would it be OK to connect the supplies to the servos from the VU pin? I'm thinking that there is a possibility it could be ok since it is directly connected to the USB.
For the signals I will use the normal GPIO pins.
Thank you in advance :-)

The circuit diagram of a NodeMCU shows that there's a schottky diode between Vusb (the voltage input supplied by USB) and the Vin pin. This has the effect of reducing the approximate 5V voltage supplied by your typical USB jack/outlet/cable to something slightly lower. In my case, the apple USB charger adapter provides 5.1V but this gets reduced to 4.76V on the Vin pin. This Vin voltage is also quite noisy. I don't know if that will affect your servos. I've run one NodeMCU from the Vin pin of another NodeMCU pin without any trouble.
The schottky diode in the NodeMCU is a 1n5819/SS14/S4(SOD_323). I'm not certain, but if this is the correct datasheet, it says it can supply 1 amp, which sounds like enough. If I were you, I'd try and see if I could get power directly from the USB source rather than taking it off the NodeMCU pin. It might work off the pin, though. Try and make sure you get a USB that supplies at least 5.1V, though. It's going to be close.
EDIT: I would also add that the NodeMCU will be drawing power, too. If you are drawing 300mA with your servos and 100-150mA with your nodeMCU, that's cutting it pretty close for most USB power sources. A Macbook, for example, can only supply 500mA via a USB port. This article says a NodeMCU can consume up to 400mA under some circumstances.
Generally speaking, I've been told that it's a bad idea to use GPIO pins to drive anything that draws a significant amount of power. I'm thinking you should maybe consider using some kind of servo driver or relay or something.


NRF24l01 with Atmega 32u4 and internal clock Will the nrf24l01 work with the Atmega 32u4 if I am using the 32u4's internal clock, or must I have an external clock source?

You ask a yes/no question, to which the answer is yes, nRF24L01 as a serial peripheral device will work as well as if you had used an Arduino UNO or any other microcontroller, provided the SPI bus is correctly initialized.

Generally you want the following in the setup() part of your sketch/program:

  pinMode(CE_pin, OUTPUT);//chip enable set as output
  pinMode(CSN_pin, OUTPUT);//chip select pin as output
  pinMode(MOSI_pin, OUTPUT);//SPI data out
  pinMode(MISO_pin, INPUT); //SPI data in
  pinMode(SCK_pin, OUTPUT);//SPI clock out

  digitalWrite(CSN_pin, HIGH);//SPI idle
  digitalWrite(CE_pin, LOW);

  SPI.setBitOrder(MSBFIRST);//SPI Most Significant Bit First
  SPI.setDataMode(SPI_MODE0);// Mode 0 Rising edge of data, keep clock low
  SPI.setClockDivider(SPI_CLOCK_DIV2);//Run the data in at 16MHz/2 - 8MHz
  SPI.begin();//start up SPI library


Reading Two Quadrature Encoder using a single Arduino Due I am working on an autonomous robot in my summer vacations. I am currently working on running the motors of my robot in a closed loop. In order to do so, I have to interface two Quadrature encoders of the motors with the Arduino Due that I have. My motor encoder have 3200 Edges per Revolution. I have read the Atmel SAM3x8E datasheet and have successfully tested one encoder in Arduino IDE. It appears that TIOA0 and TIOBO are used to read PHA and PHB of of one Encoder which correspond to Pin 2 and 13 of Arduino Due. I am not using Index pin (TIOB1).

It seems that I can only interface 1 quadrature .Is their any way I can use Quadrature decoder to read 2 encoders instead of one. As I have stated earlier I am not using the index pin. So, maybe there might be a way to decode to encoders using the three available pins as shown in the above diagram. I don't want to use Interrupts to do this job.

Here's is the link of SAM3x Manual:
http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf

Link of Motor that i am using:
www.pololu.com/product/2824

According to Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483 and referenced excel sheet with Device to No of QDEC channels it seems to have two of them. However in DUE almost none of interesting devices are wired to headers completely (Extmem, SD interface,...)
However TIOA6 and TIOB6 should be on pins 5 and 4
Pin configuration should be something like this:
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

And TC0 is pretty much same as TC2, so just copy&paste and change TC0 to TC2
Full config:
  REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
  REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

  REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC0_RC2   = F_CPU / 128 / 1;
  REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
  REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

  REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC2_RC2   = F_CPU / 128 / 10;
  REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
  REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;


Read temperature (DS18B20) with the ATTiny85 I'm trying to read the temperature of a DS18B20 with my ATTiny85 - but I'm getting rubbish data :D

I should have gotten ~22 degrees, but I'm getting 129! I followed this tutorial i found here, but maybe there is something funky with the ATTiny85?

I would suggest it has to be the clock speed or memory. Whilst you can program the ATTiny85 with the Arduino IDE, it will take up quite a lot of its flash memory. There is a thread on the Arduino form here which might help pinpointing the issue.

One solution is to write it in AVR-C but I don't know if there is an easy way (or a library) for the 1-wire. I think you'll have to do it with the 1-Wire library alone as the DallasTemperature library is too much for the 8Kb of memory you have to play with.

Please feedback any breakthroughs you make as this is a nice project, the ATTiny is an awesome little chip...


Problem with powering ublox NEO-6M GPS module Firstly, I'd like to mention that I'm a beginner. This is the first time I've worked with a GPS module. The serial monitor is completely empty when I upload the following code to my circuit:

#include <SoftwareSerial.h>

// The serial connection to the GPS module
SoftwareSerial ss(4, 3);

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

void loop(){
  while (ss.available() > 0){
    // get the byte data from the GPS
    byte gpsData = ss.read();
    Serial.write(gpsData);
  }
}

Things I might've done wrong and some things I'd like to mention:

As you can see, I connected the module to 5V pin of Arduino but the datasheet says:

The reason why I think this might not be the case is that there are multiple projects on the internet that have used a circuit like mine.
I've placed my module on the window edge so that it can get a good line of sight. I'm yet to try it outdoors.
After reading the datasheet, I tried a potential divider using resistors to get 3.3V and the result is still nothing. I later realized that this was probably a really silly thing to do since I created an unstable supply which is not suitable for the module.
For cold-start conditions, how long can it take to lock to a satellite? I've waited several times for half an hour each time only to get no result in the end. Can it take more than that? Should I wait?
What can I use to supply constant 3.3V to the module? Are there any special power supplies for GPS modules?
Is it possible to tell if my module is damaged just by seeing?

The module may very well be dead now, due to giving it 5V.

But depending on which board the module is mounted on, there might be a voltage regulator that expects 5V. Check the specifications for the board you bought.

A window means that at least 50% of the sky is blocked by the building. The module might not be able to get a signal from enough satellites for a cold start.
A voltage divider only works if there is constant current. As you've noted, you just created an unstable power supply.
The datasheet says 27 s but that is probably with a clear view of the sky.
Next to the 5V pin on the Uno is a 3.3V pin. How about using that?
Visually, no. But the Arduino should be able to communicate with the module if the module still works, regardless if the module has a GPS fix or not.


Is it possible to upload previously compiled binary? I have a number of sketches that I keep wanting to load into the Arduino but I don't necessarily need to recompile them because I haven't changed anything since the last compile. Since the compile takes a minute or 2 each time, this would save me some waiting.

I can see that the IDE has the option to "Export Compiled Binary", but doesn't seem to have the converse option of Uploading a previously compiled binary. Is there any way to do this?

Yes!
Its possible that you can upload a previously complied binary, using

AVRDUDE - a command line utility which is actually used to upload binaries, behind the arduino IDE.

You can find AVRDUDE in
Arduino folder > hardware  > tools > avr > bin

This some documentation for AVRDUDE
http://www.nongnu.org/avrdude/user-manual/avrdude.html

else simplest thing you can do is turn on verbose output during upload and watch for a command in the end with AVRDUDE in it along with the path of hex file, just copy paste &  run the same command in CommandLine; your task is accomplished.


NRF51822 ± Arduino Uno / ATmegaXXX? Hello I want to make a simple home automation project and I'd like to use an arduino uno for prototyping and later a atmega for deployment. I need some sort of a mesh communication method. I was thinking about the NRF51822 chip but I can't find any arduino libraries for it.

You can use the NRF51822 as module with AT firmware attached to Arduino. Then you need only the AT commands reference and some examples how to send AT commands and parse the response.

Or you can use the 32-bit ARM cortex-m0 micro-controller inside NRF51822 with Arduino nrf5 package. It requires a programmer/debugger hardware for sketch upload.


Equivalent of millis() in Atmel studio This code It works in atmel studio.But this millis function is starting to run 31-34 miliseconds behind of arduino millis fuction.Why?I am adding picture.

Picture: https://imageshack.com/a/img922/3060/umtNJp.jpg

Update 2

#define F_CPU 8000000UL
#include <avr/io.h>

#include <avr/interrupt.h>

#define clockCyclesToMicroseconds(a) ( ((a) * 1000L) / (F_CPU / 1000L) )
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
// the fractional number of milliseconds per timer0 overflow. we shift right
// by three to fit these numbers into a byte. (for the clock speeds we care
// about - 8 and 16 MHz - this doesn't lose precision.)
#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
#define FRACT_MAX (1000 >> 3)
volatile unsigned long timer0_overflow_count = 0;
volatile unsigned long timer0_millis = 0;
static unsigned char timer0_fract = 0;

volatile uint8_t count;

ISR (TIMER0_OVF_vect)

{

    unsigned long m = timer0_millis;
    unsigned char f = timer0_fract;

    m += MILLIS_INC;
    f += FRACT_INC;
    if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
    }

    timer0_fract = f;
    timer0_millis = m;
    timer0_overflow_count++;

}

unsigned long millis()
{
    unsigned long m;
    uint8_t oldSREG = SREG;

    // disable interrupts while we read timer0_millis or we might get an
    // inconsistent value (e.g. in the middle of a write to timer0_millis)
    cli();
    m = timer0_millis;
    SREG = oldSREG;

    return m;
}

int main (void)

{
    DDRB |= (1<<0);
    TCNT0 = 0;
    count = 0;
    TCCR0B |= (0<<CS02) | (1<<CS01) | (1<<CS00); // PRESCALER 64
    TIMSK0 = (1<<TOIE0);
    sei();

    while(1)
    {
        millis() to uart.

    }

}

The millis() function is defined in the Arduino Core for AVR architecture, specifically the wiring.c file.

You can see that timer0 is setup with various parameters for prescaling and interrupt triggering and handling of timer0 overflow such that a variable called timer0_millis contains the number of milliseconds since the sketch started.

The millis() function basically returns that timer0_millis value.

If you wish to make use of the function in AVR Studio, then you would need to include the same kind of timer0 setup and interrupt/overflow handling that the Arduino core does.


How many LED Strips can we connect to an Arduino Uno? Is there a way to connect 1-3 meters worth without needing extra parts (relays)? I am looking at Adafruit to purchase some LED strips for a mod for my computer case, and want to power it with an Arduino.

I am looking at the Uno, but the Mega looks good too.  I hear the Uno is good because if the chip fries, you can just replace it easier than the Mega's chip.  I did hear that the Uno chip had issues, but that was a 2013 post.

Anyways, I am essentially looking to connect about a foot of 144 leds/m to the front of my case, and connect that to the Arduino.  I will then be lining the inside of my case with about 12-15" per side (x4 sides) of 60 leds/m so I wanted to connect that to another part of the Arduino.

I read that each led takes something like 6mA or 60mA each, so that is what we should watch for.  I was trying to search for this question that others asked, but people were looking to connect a lot of strips, and needed relays and whatnot, so I wanted to make sure the Arduino itself could power about 1.5 to 2 meters of Led strips in at least 2 different strip configs (or whatever you want to call them).

I also am curious if there will be an issue programming each strip setup or, if it just is a little more work to get it setup?

Since this is a computer cause led setup, I'm not sure if I should go USB power, or a wall charger?  What is the recommended approach for something like this?

I will definitely be reading up more tutorials and all that important stuff, but I want to buy the stuff now since I realized there's a cyber Monday deal going on, so I don't want to miss out...

Any help is appreciated, thank you!

Yes, the current draw is the main factor here.  That's not really an Arduino issue though, as I will enlighten you about later on when I talk power supplies.

I assume, since you don't mention what the LEDs are, that you are talking about strips of WS2812 "NeoPixel" LEDs (the ones where you can control the colour of each and every individual LED).

I would recommend keeping all the LEDs as one single strip.  That doesn't mean you can cut the strip into segments, just join the ends to each other using wire in one chain.  That way you just have one chain to deal with in the Arduino.  Running multiple chains can be somewhat more resource hungry and I'm not even sure it's possible on an Arduino.  So keep it all as one long chain split into chunks and re-joined with wire.

Now for power.  Your computer has a big powerful power supply in it.  That gives a very good regulated 5V supply with many many amps available.  More than enough to run hundreds of LEDs.  By all means run the Arduino from USB (makes for easy programming - inspect your motherboard, it may well have an internal USB connector that would be ideal (I know mine has).  And then run the LEDs themselves off the +5V direct from the computer's power supply.  A spare hard drive power connector could be good for that.


Ruby and Arduino over Serial I'm trying to send data over serial and pick it up in a ruby script. I'm using the serialport gem (https://rubygems.org/gems/serialport) as stated in the Arduino docs (http://playground.arduino.cc/Interfacing/Ruby).

My question is, I'm trying to print out some gyroscope data, particularly the x, y, and z. This is what my arduino sketch looks like:

void setup() {
  Serial.begin(9600);
  // ... do some gyro stuff here
}

void loop() {
  gyro.read();

  Serial.print((int)gyro.g.x);
  Serial.print(" ");
  Serial.print((int)gyro.g.y);
  Serial.print(" ");
  Serial.print((int)gyro.g.z);

  delay(500);
}

My ruby script is pretty straight forward as well:

require "serialport"
port_str = "/dev/tty.usbmodemfa141"
baud_rate = 9600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE

sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
while true do
  message = sp.gets
  if message
    message.chomp!

    puts message
  end
end

However, the output that I get is choppy. What I mean by that is that the numbers don't come out as a single line as I intend:

52 9
5
250
 -28
 85
25
9 -5
1 69

Even if I replace it with "Hello World", it'll come out as:

He
llo
Wor
ld

or similar.

Any ideas why? Thanks in advance for any help.

Firstly, let's look into documentation for Ruby IO#gets:

  Reads the next "line" from the I/O stream; lines are separated by sep ...

Secondly, look into documentation for Arduino Serial.print:

  Prints data to the serial port as human-readable ASCII text ...

Finally, you don't print new line char \n in your "arduino sketch" above.

I recommend you to use Serial.println in the last line from your sketch:

void setup() {
  Serial.begin(9600);
  // ... do some gyro stuff here
}

void loop() {
  gyro.read();

  Serial.print((int)gyro.g.x);
  Serial.print(" ");
  Serial.print((int)gyro.g.y);
  Serial.print(" ");
  Serial.println((int)gyro.g.z);

  delay(500);
}


What are possible issues when moving Arduino to another microcontroller? When Arduino was conceived AVR was very much the best 8-bit controller available. But we're 10 years on now, and still using the AVR, despite lots of better microcontrollers available, notably ARMs. In particular M0 and M0+ cores are a lot cheaper, yet are a lot faster and have many more features than AVR.
For instance the NXP LPC824 has more serial buses, more A/D channels and higher A/D resolution, is almost twice as fast as the AVR, yet costs 30% less. (Granted, it doesn't have EEPROM, but you can have that for 20 cents.)

So I was wondering if there are particular issues which prevent the use of more modern microcontrollers on Arduino.
One difference may be Vcc, which is 5V for AVR and 3.3V for ARM. But given that more peripherals work at 3.3V this seems more to be an AVR issue than an ARM issue.

PS: I'm aware of Arduino Due, but that one costs twice as much as a Uno. I'm talking about controllers which price-wise can compete with AVR.

There is NO best 8 bit or 16 or whatever bit uC (micro controller).
There always have been "better" ones and there always will be and better changes with your need as well as with time.

If you want or need a faster or more capable processor, use one.
For many tasks the existing AVR processors are very fine indeed.

A number of people are making Arduino-like uC's using ARM right now.
You can buy them 'off the shelf'.

Running "Arduino" code is where issues arise:
If you are willing to run 100% standard Arduino code applications will usually run well on the new uC.
If applications use precompiled libraries and you wish to use eg an ARM it will not run.
If you recompile the libraries and they are written in a compatible language flavor (C or whatever) then they MAY work for your new processor.
If they use assembler then they will not work in essentially all cases.

But, existing 'Arduino' hardware can use the high level language of your choice.
A new processor with a compatible compiler will compile eg C code that runs on Arduino hardware BUT port locations, register control methods etc need to be correctly allowed for.

It gets harder and harder as you try to fit the new giants into the old not-so-giant framework. Somewhere along the way it is easier to give up the attempt and use the Arduino for what it is good for and the 'new' processor where necessary.

Whatever the Arduino did well when new it still does well.

In most cases the speed, peripherals and memory capabilities are entirely fine for tasks that people who wish to use it wish to do.
The main issue is that an Arduino is not something it is not, just as a small family car is not a bus or a sportscar. Use the car where it is useful and use a bus or sportscar when necessary.


Cannot get pins on esp 8266 adafruit wifi module to read HIGH on pin 15 I have an esp8266 and I cannot get the value to read HIGH when 3.3v is applied to directly to pin by hand. I have an Arduino Uno powering the esp8266. It connects to the WiFi like it should, and now all I want is to manually see that when I apply 3v that the state will change from 0 to 1. Does anyone know how I can do this.

When I apply 3 volts directly to pin 15 it outputs 0. Even if I try digitalWrite on the pin and set it to HIGH it still says 0 and i serialPrint. My end goal if to use the arduino uno to fire and ouput on pin 8. On the arduino UNO side I am using a super sonic sensor. When the sensor is triggered I want to turn pin 8 on. From there I want to take pin 8 to feed pin 15 on the 8266 as an input. Before I did that I just wanted to see that when you manually apply 3v that the pin would read 1 or HIGH but no matter I do it wont change value. Once I get that value as HIGH I can send  a second request to the server like im already but now I want to say  that there was an intruder. Im not sure why the value wont change but being a beginner with arduino Im trying to keep it simple and ideally would like to wire it in this manner.

#include <SoftwareSerial.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

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

HTTPClient http;

static const uint8_t D8 = 15;
int featherPin = D8;

//int trigPin = 13;
//int echoPin = 12;
//int ledPin = 10;
//int hornPin = 11;
//
//int spaceIntruded;
//
//long duration, cm, inches;

void setup() {
  Serial.begin(115200);
  pinMode(featherPin,INPUT);

  WiFi.begin(ssid, password);

  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Waiting for connection");
 }

//  Serial.begin (9600);
//  pinMode(trigPin, OUTPUT);
//  pinMode(echoPin, INPUT);
//  pinMode(ledPin, OUTPUT);
//  pinMode(hornPin, OUTPUT);
//  delay(5000);
//  Serial.println("Armed...");

}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("yay connect");

    http.begin("http://10.150.40.121:3000/");
    http.addHeader("Content-Type", "text/plain");

    int httpCode = http.POST("Message from ESP8266");
    String payload = http.getString();
    Serial.println(payload);
    http.end();

    } else {
      Serial.println("Error in Wifi connection");
    }
//    digitalWrite(featherPin, HIGH);
    int sensorValue = digitalRead(featherPin);
    Serial.print(sensorValue);

//    if (digitalRead(featherPin) == HIGH) {
//      http.begin("http://10.150.40.121:3000/home");
//      http.addHeader("Content-Type", "text/plain");
//
//      int httpCode = http.POST("Message from ESP8266");
//      String payload = http.getString();
//      Serial.println(payload);
//      Serial.print("hi");
//      http.end();
//      } else {
//        Serial.print(featherPin);
//        Serial.println("I am not hot");
//      }

//  digitalWrite(trigPin, LOW);
//  delayMicroseconds(1);
//  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(2);
//  digitalWrite(trigPin, LOW);
//
//  pinMode(echoPin, INPUT);
//  duration = pulseIn(echoPin, HIGH);
//
//  inches = (duration / 2) / 74;
//  Serial.println(inches);
//
//  spaceIntruded = inches;
//
//  if (spaceIntruded <= 50 || spaceIntruded >= 900){
//      digitalWrite(ledPin, HIGH);
//      digitalWrite(hornPin, HIGH);
//      Serial.println("Intruder Detected!");
//      Serial.println("Sending text Notification...");
//      delay(500);
//      Serial.println("Armed...");
//  }
//
//  else{
//    digitalWrite(hornPin, LOW);
//    digitalWrite(ledPin, LOW);
//  }
    delay(30000);

}

Pin 15 is one of the boot configuration pins (0, 2, 15) and must be LOW at boot. To ensure it, dev boards with esp8266 have external pull-down on pin 15 (and pull-up on 0 and 2). To read the pin HIGH you must overcome the pull-down.

Adafruit Feather HUZZAH has 4.7kOhm resistor for the pull-down, so it is a 'strong' pull down. NodeMcu has 12kOhm resistor on io 15.

From schematics of Adafruit Feather HUZZAH

Note: setting pin as OUTPUT and HIGH doesn't make it read HIGH in code. Only INPUT pin state can be read with digitalRead (only on some MCUs digitalRead reads the same register set by digitalWrite).


Send one bit out per clock pulse received using direct port manipulation? I want to send one bit of a byte out per 'rising edge' received to an Arduino digital input. I am addressing the outputs using direct port manipulation (to achieve maximum speed), and I would like to do the same for input.

So I'm calling a function called bitBang in my main loop, sending the ready line high before moving into the function:

//Send control
PORTB |= _BV(PORTB2);
bitBang(controlByte);
PORTB &= ~_BV(PORTB2);

What I would like to do upon entering the function is listen for a rising edge to appear on the digital input port using the direct port syntax and iterate through the byte setting the data line high or low depending on the bit's value.

How can I achieve this in the most efficient way possible?

Example bit-banged SPI using port manipulation:

bitBangedSPIfast.h :

#include <Arduino.h>

class bitBangedSPIfast
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const mosiPort_;
  volatile byte * const misoPin_;
  volatile byte * const sckPort_;

  // bit masks for above
  const byte mosiBit_;
  const byte misoBit_;
  const byte sckBit_;

  // addresses of data direction register ports
  volatile byte * const mosiDDR_;
  volatile byte * const misoDDR_;
  volatile byte * const sckDDR_;

  // bit masks for above
  const byte mosiDDRBit_;
  const byte misoDDRBit_;
  const byte sckDDRBit_;

  // delay for clock being high
  unsigned long delayUs_;

  public:
    // constructor
    bitBangedSPIfast (
          // output ports
          volatile byte & mosiPort,
          const    byte mosiBit,
          volatile byte & misoPin,
          const    byte misoBit,
          volatile byte & sckPort,
          const    byte sckBit,

          // data direction register ports
          volatile byte & mosiDDR,
          const    byte mosiDDRBit,
          volatile byte & misoDDR,
          const    byte misoDDRBit,
          volatile byte & sckDDR,
          const    byte sckDDRBit,

          const unsigned long delayUs = 1)
       :
         mosiPort_ (&mosiPort),
         mosiBit_  (1 << mosiBit),
         misoPin_  (&misoPin),
         misoBit_  (1 << misoBit),
         sckPort_  (&sckPort),
         sckBit_   (1 << sckBit),

         mosiDDR_     (&mosiDDR),
         mosiDDRBit_  (1 << mosiDDRBit),
         misoDDR_     (&misoDDR),
         misoDDRBit_  (1 << misoDDRBit),
         sckDDR_      (&sckDDR),
         sckDDRBit_   (1 << sckDDRBit),

        delayUs_ (delayUs) { }

    void begin ();
    byte transfer (byte input);

  };  // end of bitBangedSPIfast

bitBangedSPIfast.cpp :

#include <bitBangedSPIfast.h>

void bitBangedSPIfast::begin ()
  {
  if (mosiPort_)
    *mosiDDR_ |= mosiDDRBit_;    // output
  if (misoPin_)
    *misoDDR_ &= ~misoDDRBit_;   // input
  *sckDDR_ |= sckDDRBit_;        // output
  }   // end of bitBangedSPIfast::begin

// Bit Banged SPI transfer
byte bitBangedSPIfast::transfer (byte c)
{
  // loop for each bit
  for (byte bit = 0; bit < 8; bit++)
    {
    // set up MOSI on falling edge of previous SCK (sampled on rising edge)
    if (mosiPort_)
      {
      if (c & 0x80)
        *mosiPort_ |= mosiBit_;
      else
        *mosiPort_ &= ~mosiBit_;
      }

    // finished with MS bit, get read to receive next bit
    c <<= 1;

    // read MISO
    if (misoPin_)
      c |= (*misoPin_ & misoBit_) != 0;

    // clock high
    *sckPort_ |= sckBit_;

    // delay between rise and fall of clock
    delayMicroseconds (delayUs_);

    // clock low
    *sckPort_ &= ~sckBit_;

    // delay between rise and fall of clock
    delayMicroseconds (delayUs_);
    }  // end of for loop, for each bit

  return c;
  }  // end of bitBangedSPIfast::transfer

Example usage:

#include <bitBangedSPIfast.h>

bitBangedSPIfast bbSPI (PORTD,  5, PIND,  6, PORTD, 7,    // MOSI port (D5), MISO pin (D6), SCK port (D7)
                        DDRD,   5, DDRD,  6, DDRD,  7);   // MOSI ddr  (D5), MISO ddr (D6), SCK ddr  (D7)
const byte mySS =  8;  // slave select

void setup (void)
  {
  bbSPI.begin ();
  pinMode (mySS, OUTPUT);
  }  // end of setup

void loop (void)
  {
  char c;

  // enable Slave Select
  digitalWrite(mySS, LOW);

  // send test string
  for (const char * p = "Hello, world!" ; c = *p; p++)
    bbSPI.transfer (c);

  // disable Slave Select
  digitalWrite(mySS, HIGH);

  delay (100);
  }  // end of loop

Reference

SPI - Serial Peripheral Interface - for Arduino


How to measure resistance of TFT Touchscreen I'm using a TFT Touchscreen shield with my Arduino UNO, and I'm running "tftpaint" example by Adafruit.

I've noticed that when initializing the Touchscreen object, a resistance value must be provided. Library default is 300, but a comment in the code says:

// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it

How should I perform such measurement? Where do I put the probes of my multimeter? FYI, my shield is this one:

As pointed out in other answers and comments, step one was trying to get a datasheet for this component. I couldn't find a datasheet for the shield, but here is the link from the vendor I bought it from, and they provided with some articles were they explained how to perform the resistance measure. However, I then noticed the answer was in the example code itself.

Btw, the shield it's indeed based on SPFD5408 as correctly suggested by user Michel Keijzers on his answer.

So, in turns out the hint to which pins were X+ and X- was actually in the example code I'm using. Here the Touchscreen object is initialized:

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

Notice the usage of constants XP and XM. The names stand for "X-plus" (X+) and "X-minus" (X-). Now if we look a couple of lines above where these constants are defined, we see this:

#define YP A3
#define XM A2
#define YM 9
#define XP 8

In particular, we see that XM (i.e. "X-") is mapped to analog pin A2, and XP (i.e. "X+") is mapped to digital pin 8.

Now, by looking at how the shield couples with arduino, we can see that analog pin A2 of the Arduino board, connects with pin labeled "LCD_RS" in the shield, and that pin 8 connects with pin labeled "LCD_D0".

This is a picture (found online) of the bottom side of the shield, were we can see the labels for each pin:

Finally, with a multimeter at those pins, I measured the resistance and it was 292 Ohms. Not so different from the default of 300 in the library, but it's still a good thing to have the correct value.


Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output? Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?

This is the Chip I have. On the chip it says ProMini R160JAC6v. and When i program it. It programs under 5V 16MHz with ATmega 328

Here is the bluetooth chip I am powering:

If you power from USB the vcc pin gives you the voltage that USB is providing. Somewhere between 4.75 and 5.25v.

If you use external power it provides 5v since that is what the regulator provides.

The current limit is either the limit of the usb port or the limit of the regulator on your board. Check the datasheet for that regulator (hint: read the schematic to find the model of the regulator).


What's in an Arduino? I've been using an Arduino Uno Rev. 3 for a few projects and would like to switch to using a bare Atmega328 chip so I can keep everything on the same board. I've seen the Arduino on breadboard tutorial which is fine, but the Arduino board itself has a lot of other components that aren't in the tutorial. I realize I can go look up the actual design itself, but I'm looking for a high level description of what most of the components are used for.

I'm not interested in programming through the Arduino IDE, so I don't need parts for serial programming and such. But I'm wondering if leaving out some other components would leave me at a disadvantage. For example, the datasheet recommends connecting AVCC to VCC with an LC circuit for ADC noise cancellation, but the arduino on breadboard tutorial doesn't mention this and I otherwise never would have known.

You did not specify what Arduino board you are talking about. It would
have been useful to tag the question with the appropriate board name. In
the following, I assume you want something similar to an Arduino Uno,
i.e. an ATmega328P at 5 V and 16 MHz.

  I realize I can go look up the actual design itself [...]

You should. There really isn't that much to it.

Let us take a look at the Uno rev. 3 schematic, and see what may be
useful to you:

ATmega16U2 and associated circuitry: This is for USB communication.
You have no use of it if you are not doing USB.
3.3 V regulator: This is for providing the Arduino 3.3V output.
Only a convenience feature, not used by the Arduino itself. You should
leave this out unless you need a 3.3 V supply.
5 V regulator. Only you know how you want to power your board.
This regulator is needed unless you have some reasonably stable
5 V supply like, e.g., a USB bus.
ISCP header: This is rarely used on an Arduino, but you are very
likely to use it in your custom board, as ICSP is the easiest way to
program an ATmega with no bootloader.
Reset button: Not always needed, as you can just power-cycle your
board.
10 kΩ pullup on RESET: Your board is very likely to work just
fine without this, but there is a little risk that you suffer from
random resets. You want this resistor on anything that is
“production”-like, for reliability concerns.
Decoupling capacitors: Just like the RESET pullup, the board may work
without them, but they provide reliability.
The MOSFET and OP-amp right before the 3.3 V regulator: This is
for automatically switching between the Vin and USB power supplies.
Unlikely to be useful on a custom board.
Ceramic resonator: For running the ATmega at 16 MHz, you need
either this or, for better timing characteristics, a quartz with
suitable capacitors.
LEDs: You know if you want them.
AREF capacitor: Only useful if you do analog readings, as it reduces
noise.


Writing analog voltages on analog pins of Arduino Can we write a analog voltage to analog pins A0-A7 of the Arduino Nano (for example)?

As in:

pinMode(A3, OUTPUT);
analogWrite(A3, 200);

No. The analogWrite(pin, val) function is reserved to PWM pins (D3, D5, D6, D9, D10, and D11 in Arduino Nano). Pins marked as "ANALOG IN" on the board can work either as analog input (to the Analog to Digital Converter), digital input, or digital output.

It is worth to note that the Arduino Nano (and any other Arduino board I'm aware of) actually doesn't have any 'true' analog output port. When you use analogWrite(pin, val) you are actually telling the Arduino to output a PWM signal with the duty cicle specified by val (100% for val = 255 and 0% for val = 0). If you actually do need a true analog output, you should consider using any form of analog lowpass filter at the specified PWM output port. Depending on how clean you want your signal to be, you could use a single capacitor or any other (a little more complex) filter.

If you don't know anything about filters, this could be a good starting point: ElectronicsTutorials - Passive Low Pass Filter

More insight about PWM in Arduino, here: EAS 199 - Basic Pulse Width Modulation


CPU information on Arduino Serial Monitor how to show the

CPU temperature,
CPU usage (percentage) and
the memory usage(percentage)

in Arduino Serial Monitor.

CPU temperature

Some Arduino boards have a microcontroller with a temperature sensor inside. For example the Arduino Uno can measure the temperature inside the microcontroller.

As far as I know, no one uses it. It is not accurate and a microcontroller should not get hot in the first place. The microcontroller or processor on the Arduino board can run at 100% load and it does not get hot.
The internal temperature sensor is not accurate enough to measure the ambient temperature.
The internal temperature is therefore (almost) useless.

See this page on the Arduino Playground and this forum thread for the internal temperature sensor.

CPU usage

There is no CPU usage. There is no idle task. The microcontroller or processor usually runs all the time at full speed.

It is possible to determine how long the Arduino board stays in delays (via the yield function).
With a external RTC clock it is possible to determine how long the Arduino board stays in sleep mode (some battery powered Arduino projects use the sleep mode).
However, those are very specific things. Perhaps a project requires to measure them, but there is no common use for them.

A good sketch is not supposed to do nothing, it is supposed to check all the inputs and check millis-timers and act if needed. The Arduino loop() function is supposed to run as often as possible to make the Arduino run fast and smooth.

Memory usage

The memory usage is something to be aware of when writing a sketch. An Arduino board has much less memory than a typical computer.

It is possible to determine the unused memory between the stack and the heap.
The function at the bottom of this page can be used to determine the amount of free memory.

I have also seen code to measure the high water mark (memory that is never used at all), but none of them work for all Arduino boards and the code is not reliable.


If a Timer is used, disabling some PWM pins, can I still use those pins for Digital write? It's my understanding that when a Timer is used on an Arduino (in my case the Arduino Mega), it can disable analog write on some PWM pins, which pins depends on the Timer being used. For instance on the Mega, pins 44,45,46 are controlled by Timer 5.  If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

If I enable Timer 5, does that mean that I can't use these pins for anything else? Or does it only mean I can't use those pins for AnalogWrite, and that I can still use those pins for DigitalWrite.

You can view the connection between the Timer and the pins as programmable. The connection is enabled by, for instance, analogWrite(). The Timer control registers have a setting for both the connection and control logic of the pin (clean, set or toggle on timer value match).

You can use the Timer to generate interrupts without connecting a pin. This is the case with micros() and millis() which get their values from a counter which is updated by an ISR on Timer 0 (overflow). analogWrite() on pin 5 and 6 connects to Timer 0 value match logic.

analogWrite() uses the Timer value match and connects the pins. Enabling only the Timer (as you suggest) will allow you to use the pins with digitalWrite(). You can also use the Timer ISR for overflow. The Timer prescale is set for analogWrite().

Cheers!


Calculating SpO2 using pulse sensor I was wondering is there a way to calculate SpO2 using a pulse sensor?
I calculated BPM and stress before with pulse sensor and now I want to calculate SpO2.

Link to Pulse sensor manual

For measuring oxygen saturation (SpO2) with a pulse sensor, you need to use the fact, that hemoglobin, that carries oxygen, will reflect in different light wave lengths, as hemoglobin, which doesn't carry oxygen. But that also means, that you need to use light in at least 2 different wavelengths. Common are one red (about 660nm)(though green may also work) and infrared (about 940nm). When lighted sequentially with both LEDs, you can measure the refection of both parts and calculate the ratio between them (SpO2).

But your sensor only has 1 LED, which is green. So you cannot measure SpO2 with this sensor. You need one fitting the above description.


What is the easiest way to count how many global variables are in your sketch code? I have a fairly complicated sketch with about 1k lines of code. I should also say that I'm not a programmer by trade...

As I go over my code and try to make it more efficient, it'd be good to know how many global variables are in my code and whether/if all of them are necessary as global. So:

1 - Is there an easy way to count how many global variables you've used (again, imagine complex code by a non-coder), and

2 - Is there an easy way in the Arduino IDE to jump to it?

1 - The number of variables is not important, but the number of used memory (in bytes) is important. That is shown at the bottom of the Arduino IDE by the compiler when verifying or uploading a sketch.

2 - It is not possible to go to, for example, the largest global variable. You can use the search function to search for something.

For a small microcontroller, for example a Attiny or Atmega8, every byte that uses memory can be important.

For a Arduino Uno and larger, the optimization is done more globally.

To optimize for ram, look for the hungriest memory eaters:

For the Arduino Uno and other avr microcontrollers, the text with
Serial.println can be put in PROGMEM with the F() macro.
Many String
objects might need a lot of heap memory.
Arrays can get large
quickly.
Arrays of large elements (float, struct) can get large even
more quickly.
The SD library uses a lot of ram memory. There is a small version
of the SD library.
Some graphical libraries for displays use a lot of memory.

Try to avoid to save a single byte, unless you check the resulting memory usage. The compiler can optimize code in a way that conflicts with someone trying to save a byte.

When an integer is changed into a byte,
perhaps all the calculations are still done with integers and the
compiler needs more memory to convert from byte to integer and back.
Perhaps that integer was only used in registers and
did not use a memory location.
A 'const' integer uses probably no ram memory at all.

Final tip: Don't be afraid to upgrade to an other Arduino board with more memory. If you project uses almost all the memory, then it is not possible to add something to your project. When the project runs for a while, you might want to add an extra sensor or extra functionality.


Deprecated Conversion error I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming
How to remove it?

C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino: In function 'void updateState(byte)':

C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

I am writing a code for ARDUINO UNO in arduino 1.8.1 and the following error is coming How to remove it?

C:\Users\Mahe\Documents\Arduino\sketch_mar09b\sketch_mar09b.ino:243:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   DisplayInfo("RFID Scanner", "Starting up", HIGH, HIGH);

To give a detailed answer the full prototype for DisplayInfo() is needed. The issue is that the literal strings are const char* and the function parameters are declared as char*.

The correct way to fix this would be to update DisplayInfo() so that the parameter types are const char*. The dirty fix is to cast the parameters in the call.

   DisplayInfo((char*) "RFID Scanner", (char*) "Starting up", HIGH, HIGH);

But I would not recommend that.

Cheers!


Increase the resistance of a photoresistor with increase in light intensity I'm building a laser tripwire of sorts and instead of shutting up when the laser points on it (which is essential for my project) it beeps louder.

Here's the code

int buzzPin = 11; // buzzer connected to digital pin 11

void setup() {
    pinMode(buzzPin, OUTPUT); // sets the digital pin as output
}

void loop(){
    if(analogRead(0) < 750){ // this number depends on calibration of the photocell
        digitalWrite(buzzPin, HIGH); // turns buzzer on
        delay(5000); // waits for 1 second
        digitalWrite(buzzPin, LOW); // turns buzzer off
    } else{
        digitalWrite(buzzPin, LOW);
    }
}

Arduino can not measure resistance. It can measure voltage.
To measure resistance you can convert resistance to voltage using a voltage divider.

In Arduino world a voltage divider consists out of 2 resistors in series between 5V and gnd. The connection to the 2 resistors is connected to a analogue pin.
Depending whether your LDR is connected to gnd or 5V the measured value on the analogue pin will go up or down with the resistance of the LDR.

In other words swap the resistor and your LDR from position.


How can Arduino know Wire.available() is true or false? In this part of code

void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

How can Arduino know that Wire.availble() is true or false?

I thought that when the microcontroller "reads" the value from the sensor, in pieces of 8 bits, he reads from 0 (n) to 5 (n+5) at the I2C address of the MPU-6050, and when he increments 6 it finds nothing, but this is my conclusion, i am not sure about it.

I am studying how Serial.available works and how the circular buffer works for the data comunication, because available() inherits from the Stream utility class.

The entire code is the following taken from  this question

  #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

Minor Question

I am trying to undestand the difference between the register and the device address, but i did find anything on my book.

The simple answer is that the Arduino Wire library has an internal buffer, and it can bring in characters and have them sitting there ready for you to pick them up.

It can also sense a total disconnect because of the way it uses both data pins to establish communications.  It is more like a current loop than a simple one-is-transmit-and-the-other-is-receive.  If it disconnects the Arduino knows it is not available.

Kudos on going to the documentation, by the way.


Is it possible to hookup two ultrasonic sensors to one Arduino Uno unit? I found a couple of projects using Ultrasonic Distance sensor with Arduino Uno. Is there a way to connect two or more sensors on the same Arduino Uno?

Yes, it is certainly possible.  There are a few things you need to be aware of:

1)  The Arduino UNO is 5V by design.  Many sensors (not all, but many) are 3.3V devices.  So connecting them to a 5V pin could damage them.  Since you seem to be just starting out, I'd recommend sticking with 5V tolerant sensors.

2)  The Arduino UNO only has so many pins available....obviously.  Different sensors require different amount of pins to 'work'.  For example, a temperature sensor might work with the SPI interface.  Another sensor might require 8 pins.  So if you start running out of pins, you need to think about other challenges like using shift registers, multiplexers, etc.

3)  Don't be afraid to experiment.  I suggest buying a genuine Arduino UNO to support the project.  Maybe buy some cheap Chinese ones to experiment on...in case you fry on of those.

In theory, the sky's the limit when it comes to "how many".  In real life, if you start going over a handful, dozen, etc. then you might want to rethink your design.


relay working problem I am using circuits.io with Arduino. my program is to blink the led with 2 seconds delay. The led in the circuit blink according to program but the bulb does not blink. I am very weak in electronics. This is what i starting to learn from the scratch. the problem here is the bulb doesnt blink according to the program. which is meant to blink. i have uploaded the circuit image below.. . thanks in advanced.

If you wire up your circuit as shown below, the bulb and the LED should flash together.


how long should interrupting signal last? I want to apply the interruption of a program with a RISING signal from a pin. How long should the signal rise to be considered as the interruption?

If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. Shorter pulses are not recommended to generate an interrupt.

Source (page 91, chapter 17.2.1 "External Interrupt Control Register A")


How to program Arduino LCD shield with Python? so I want to run a Arduino LCD shield with Python code..But after having some research on the Internet, I can not found any tutorial, some just give some basic code with LED.

And one things that how can I add a LCD library (LyquidCrystal.h in Arduino code) if i program in Python.

Thank you guys very much.

It's like @chrisl wrote in the comments. You cannot program Arduino with python.

You can however upload an open source Firmata protocol implementation onto the Arduino and then write python code on your PC that will send commands to the Arduino by USB cable to tell it what to do.

This way you actually execute your code on PC, but control Arduino pins. Only drawback is that you need to have a PC connected to the Arduino at all times. This is not very practical.

There is a really nice tutorial here

Example python code looks like this:

import pyfirmata
import time

board = pyfirmata.Arduino('/dev/ttyACM0')
while True:
    board.digital[13].write(1)
    time.sleep(1)
    board.digital[13].write(0)
    time.sleep(1)

I'm afraid that only solution to controlling LCD shield this way without writing any C is to write the entire LCD library in python basing on pyfirmata calls to control the Arduino pins. It's not as hard as it sounds, and even a beginner could easily succeed.


I2C interference SENSOR(SCL+SDA) and MasterSlave comm I am building a weather station with an Arduino slave (dedicated to a rain gauge - depicted below as a reed switch) and a NodeMCU master with some additional sensors.

One such sensor, a BMP280 uses D1 and D2 as SCL and SDA, while slave control is using D3 and D4 for communication with Arduino.

When I enable Wire.begin for slave communication, my BMP280 readings go nuts

#include <Adafruit_BMP280.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bmp;

// masterSlave
#include <Wire.h>
#define I2CAddressESPWifi 8
...

void setup() {

    if (!bmp.begin()) {
        Serial.println("Could not find a valid BMP280 sensor, check wiring!");
        while (1);
    }

    // masterSlave - generates problem with BMP280...
    Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

  BMP280 Temp = -136.42 *C

  Pressure = 125136.25 Pa

as opposed to this reading when Wire.begin is commented out.

    // COMMENTED OUT FOR DEBUGGING
    //masterSlave - generates problem with BMP280...
    //Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

  BMP280 Temp = 20.01 *C

  Pressure = 93464.36 Pa

I attempted setting D3 and D4 to LOW while reading from BMP280, but it had no effect on readings.

The Adafruit BMP280 library uses the Wire library. It calls begin() at default pins (D1, D2). And then you begin() the same Wire object at different pins. From that moment the BMP280 library can't communicate with the sensor.

The I2C (a.k.a. TwoWire or Wire) is a bus. Many devices can be wired to the same pair of pins. They must listen on different addresses. So wire both devices to the D1, D2 and use in slave Arduino an address different then the address of the sensor.

The esp8266 and the sensor are 3.3 V devices. The Uno is a 5 V device. You should use logic level conversion on SDA/SCL to Uno.


Board recommendations for GPRS/GSM for 'on the go' I have been tasked to find a way of communicating to a webservice from my microcontroller - yay!

With little-no real grasp on sms/etc (due to not ever 'using' it before), it appears that my knowledge of GPRS is, well, none existent.

So, I've come here in hope that someone could tell me if there is such a way for a microcontroller to 'send data out' though, well, a 'sim card' via an sms message.

This has left me a little lost If i'm honest.

My project involves 'tracking' a vehicle (still working on finding a GPS module for that), and then sending the coordinates back to HQ at hourly intervals (via text message).

So, My obvious question is this: What GPRS sim card module will allow me to do this?

I read here, although the accepted answer there for a chip requires external power, and so is of no 'true' use to me as the whole unit needs to be powered and left 'unattended' for long hours at a time.

seeing as I also need to 'monitor current location' of the board, I am also in need to obtain a GPS location.

I was thinking that mobile phones have both of these cababilitys - is this done with a 'sim card module', or is there a way of 'one module does both - send an sms AND can also gain current GPS location'?

Sorry if this is too broad, but I'm certainly not 'gifted' in knowing too much about these technologies (esp. when all these acronyms use similar letters).

Any advice / input here would be very helpful.

I have a project that have the same idea that yours.

I used Ublox NEO-6M GPS Module for GPS tracking, the module cost in a range from $6 to $13 USD(it depends from where the seller ships, china o USA) in EBAY. You can connect it via UART.

For the internet I used a SIM800L V2.0 5V Wireless GSM GPRS MODULE, you can buy it from EBAY too, it cost no more than $10.00 USD, and you can connect to internet or send SMS using AT commands.

I used a combination of arduino and Raspberry pi zero, also I send the GPS data to a webserver (I pay 5dllr/month for a VPS) and then I can track using google maps.

Thats the basic information, you can use it to start working.


Using Arduino libraries with ARM based microcontroller A week ago I started messing with LoRa. I got my STM32L151 IM880A kit.

Company that provided SX1272 LoRa modem chip (used in kit), provided some libraries, but lots of functionalities are still not implemented and is still not suitable for use in multi P2P aplications.

After googling I came across Libelium company which used SX1272 chip in their products design and they provided useful set of libraries that provides lots of functionalities and also implements some sort of LoRa frame protocol stack ideal for use in P2P applications.

The problem is that I'm using STM32 in my project and Libelium libraries are written for Arduino. So I was wondering if there is a smart way to port Arduino libraries so I could use them in my STM32 Keil projects, since the libraries seems huge.

Tips, hints, links would be appreciated (I don't have experience in using Arduino and I'm not familiar with Arduino library structure).

Every time I work on a project I use arduino libraries and port them to my micro controller.
I used sublime text editor with multiple selection and editing(ctrl-d). Then I copy the arduino code to both sublime and my uC IDE then compile it in the IDE, scroll up to the first undefined function and add its definition to the code or modify it using sublime multiple editing and selecting (like digital read and write was in my opinion useless). After that update the file in your IDE and compile again.

You would do that till you have finished and it would take some time.