How to power multiple LEDs with a microcontroller I currently have a "tiny" setup and want to put a few (~20-30) 0402 LEDs on a 1:87 scale car. My current setup is an ATtiny85 USB Mini Dev Board powered by a 90mAh 3.7V LiPo battery which is connected to a TP4056 5V micro USB Lipo battery charger:

To my bitter disappointment one cannot connect the leds in series. I've read about charlieplexing which was a little mind boggling for me to comprehend.

I was going to break down the leds and pins as follows:

P0 - headlights (2x white 0402 LEDs) +  tail lights (2x red 0402 LEDs) - in series - in parrallel
P1 - blinkers (4x amber 0402 LEDs) - in series - in parrallel
P2 - siren (12x amber 0402 LEDs) - in series - in parrallel
P3 - beacon (2x blue 0402 LEDs) - in series - in parrallel
P4 - beacon (2x blue 0402 LEDs) - in series - in parrallel
P5 - beacon (2x blue 0402 LEDs) - in series - in parrallel

Question:

With space being limited inside the model car how would I be able to
drive 20-30 LEDs with the above set up?
I am in doubt that the models in the video use charlieplexing and use a similar microcontroller, how would they be doing this?
Would it be better for me use something like a Pro Micro ATmega32U4 5V 16MHz and spread the LEDs across the 16 pins (ie 2 LEDs per pin = total of 32 LEDs)?

I see no reason why you would not be able to light 30 LEDs.
ATtiny85 only has 5 pins for use (unless you want to use the reset pin as well in which case hell will cover you). So with charlieplexing you are going to be able to address 20 endpoints. (where each endpoint might consist of multiple LEDs)
But beware. You CAN address 20 endpoints but you CANNOT light every combination simultaneouly. You will have to work out if there is a constellation that allows you to light all lights you want in the same time or you will have to use one of the timers to toggle between different lights. I don't know how well it works thou.
I have managed to use a timer on an 8MHz device to drive 4 LEDs at 400Hz directly without charlieplexing and not using PWM. So I assume it will be possible but might be flickering.
It would definitively be easier. I always recommend to stick to things that are well known and widely used. That would fit your ATmega32U4.

Make sure you layout your LEDs and think how you want to address them and if it makes sense to join multiple LEDs to one pin and toggle them at once.


Matching incoming data with a variable I have a system where an RFID tag can be checked and Its individual 4byte UID will be printed. My task is to check if subsequent tags have the same UID and if not, print “access denied”. I'm assuming i need to use const char but I'm not sure. I get an error at if (myrfid.serNum[i] == ID) saying comparison between pointers and integers are forbidden.
Any sort of clarity would be appreciated, thanks!

(Code is only a section from the for loop)

void loop()
{
    int i;
    const char ID[] = "111 11 11 11";

    cardpresent = myrfid.isCard();

    if (cardpresent && ! lastcardpresent)
    {
        if (myrfid.readCardSerial())
        {
            for (i = 0; i < 4; i++)
            {
                if (myrfid.serNum[i] == ID)
                {
                    Serial.print("Acess granted ");
                }
                else
                {
                    Serial.print("Acess not granted ");
                }
            }
        }
        Serial.printf("%3d ", myrfid.serNum[i]);
    }
    Serial.print("\n");

    // ...
}

The accepted way to initialize an array in C follows this example:

const char ID [] = {111, 11, 11, 11};

You can read more about it here.

You later use an array name ("ID") with no index ("ID[0]").  The C compiler assumes the programmer who uses an array name with no index is interested in the memory address of the first element of the array.  But you wanted the value in that memory location.  So you should use the array name with the appropriate index.  Guessing, it would appear you intended to use "ID[i]" in the above code fragment.


How to use capactive touch on Adafruit board in Arduino mode? I have a Trinket M0 which has three pins capable of capacitive touch, A0, A3, and A4. When using CircuitPython on these boards you can use the CapTouch Library. But as far as I can tell this does not exist for use in Arduino mode. Does anyone know how to get these pins to pick up capacitive touch? I've tried the Adafruit_FreeTouch library, but with zero documentation, it's not very user friendly. I thought I had it working with two pins, but whenever both pins detect capacity, the capacity is divided between them, so both pins report about the same capacity.
Any help would be greatly appreciated.
This question does seem like a duplicated of Built-in capacitive touch detection with SAMD21 development board (Arduino Zero Compatible) but there was never a solution.
Thanks!

Example code for capacitive touch on Trinket M0.  Note: make sure to install the Adafruit FreeTouch library.
// touch - Capacitive touch demo using FreeTouch. Trinket M0 version.
// Note: the pin silkscreened 1 is Analog Pin 0.

#include "Adafruit_FreeTouch.h"

Adafruit_FreeTouch qt_1 = Adafruit_FreeTouch(A0, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);

void setup()
{
  // Initialize A0 as a touch sensor
  if (! qt_1.begin())
    Serial.println("Failed to begin qt on pin A0");
}

void loop()
{
  int counter, result = 0;
  counter = millis();
  result = qt_1.measure();
  Serial.print("QT 1: "); Serial.print(result);
  Serial.print(" (");  Serial.print(millis() - counter); Serial.println(" ms)");
  Serial.println("\n*************************************");
  delay(200);
}

Information about the parameters for the constructor can be found at: https://forums.adafruit.com/viewtopic.php?f=8&p=610501  and are paraphrased below incase the link goes dead.
The parameters for the constructor are:
p - The input pin connected to the sensor.
t - How much to oversample the input.  One of the following:
OVERSAMPLE_1
OVERSAMPLE_2
OVERSAMPLE_4
OVERSAMPLE_8
OVERSAMPLE_16
OVERSAMPLE_32
OVERSAMPLE_64

Oversampling is a process of taking several measurements, finding the average, and reporting that instead of the actual readings. It's way of reducing noise, but also improves the accuracy of the measurement. The average value of noise is zero (if it wasn't, it would be a source of free energy), so the more readings you add together, the closer the noise error in the measurements approaches zero.
There's another side-effect of adding noise to measurements though: it dithers the sensor output around the real input value. If I have a window comparator that only measures "below 1v" and "above 2v", and feed it a signal at 1.1v plus a couple of volts of noise, I can expect to see about ten "below 1v" outputs for every one "above 2v" output. The noise pushes the signals above and below the thresholds, but vanishes if I take the average of a large enough sample. Statistically, getting a 10:1 improvement in resolution like that would take about 64 readings to make the noise error small enough to ignore.
Oversampling takes longer though, so there's always a tradeoff between how much you can do and how long the signal will remain stable.
r - The value of the resistor that will discharge the touch pad.  One of the following:
RESISTOR_0
RESISTOR_20K
RESISTOR_50K
RESISTOR_100K

f - Frequency mode.  One of the following:
FREQ_MODE_NONE
FREQ_MODE_HOP
FREQ_MODE_SPREAD
FREQ_MODE_SPREAD_MEDIAN

For systems that take repeated measurements, there's one kind of noise that doesn't average to zero: noise that occurs at the same frequency as the sampling rate. There are all sorts of videos that show the effect of a camera being in sync with the thing it's recording.. this one is especially nice:   https://www.youtube.com/watch?v=uENITui5_jU
For capacitive sensors, things like induced signal from fluorescent lights can create noise, and if the lamp frequency is just slightly off of your sampling frequency, the touch system will think it looks like a series of touches.
(If you have an oscilloscope, hold the tip of a probe between your fingers and put your hand within a foot or so of a fluorescent light.)
One way to prevent that is to change the sampling frequency. You can shift it up and down in a predictable pattern, hop from one frequency to another, or add some random jitter. Atmel's QTouch library supports all those options, but 'NONE' (fixed frequency readings) is the simplest.


Modifying Print.h on a Mac Most of my Arduino work has been on a PC, but now I am on a Mac. I need to modify Print.h to give me printf facilities, as detailed here.

I can find Print.h buried within my application files, but changing it has no effect. A search across my disk reveals no further Print.h files.

Where on a Mac should I find and edit the Print.h file?

Can someone tell me what I am missing please?

Thanks,

Martin

Each hardware package has its own version of Print.h in the cores folder. The Arduino IDE installation includes a copy of the Arduino AVR Boards hardware package but that package will not be used if you installed a different version via Boards Manager (Tools > Board > Boards Manager) or if you have a board selected from the Tools > Board menu that is not part of the Arduino AVR Boards package. Operating systems seem to like to hide the folder that Boards Manager installs the hardware packages to by default, which makes things more confusing.

The easiest way to find the location of the active hardware package, and thus the Print.h you want to edit is this:

Select a board of the hardware package you want to locate from the Tools > Board menu.
File > Examples > SPI > BarometricPressureSensor (or any other example sketch of the SPI library)
Sketch > Show sketch folder - this will open the BarometricPressureSensor example sketch folder.
Navigate up 4 folder levels to the architecture folder.
Open the cores subfolder of the architecture folder.
If there are multiple folders inside the cores folder you will need to open boards.txt (which is located in the architecture folder) and find which core library your board is using, which is specified by the build.core property. Most hardware packages only have a single core library so this should not be necessary.
Open the core folder. There you will find Print.h.

The reason I selected the SPI library example is because this is a hardware specific library that is bundled with all hardware packages I've encountered. If you encounter a hardware package that does not bundle an SPI library you would want to open the example for another hardware specific library such as Wire, SoftwareSerial, or EEPROM.


How to convert digital signal to analog value I have spwm output from arduino, and when i read on analogread it shows only 1023 and 0, because it is digital signal.
Is there any way to convert these spwm value into analog value reading

The problem seems to be clear to you: for slow systems a pwm signal can be considered analog, but measuring at higher rates and without a filter reveales the digital nature behind pwm and all you see is either logic high (1023) or low (0).
Possible solutions are:

apply a filter in hardware (LC low-pass)
apply a filter in software (e.g. by calculating a running mean)
attach interrupts to the rising/falling edge of your signal and measure the high/low time to calculate the duty cycle

Which of those options to choose will mainly depend on the PWM frequency you want to measure. For low frequency I recommend option 3 (special cases are duty cycles around 0% and 100% as there are no edges), for higher frequencies I would use option 1/2.


MAX7219 not behaving as expected I have 2 rows of 12 MAX7219 connected in series with DOUT to DIN (rows are isolated). Now the thing is I am using LedControl Library to work with it. The problem is the last 4 Matrices on both the rows don't work. The sequence in my code is like this where (row, column, matrix) is used to define the row and column of the matrix and I am talking about a single ROW from two ROWs of 12.

Sequence in Code      What Happens
----------------      -----------------
(0, 1, 0)             (0, 1, 0)
(0, 1, 1)             (0, 1, 9)
(0, 1, 2)             (0, 1, 1)
(0, 1, 3)             (0, 1, 10)
(0, 1, 4)             (0, 1, 2)
(0, 1, 5)             (0, 1, 11)
(0, 1, 6)             (0, 1, 3)
.                     .
.                     .
.                     .
(0, 1, 11)            (0, 1, 8)

Now I can understand why does this happens. This code works like this even if the Device Count is 8.

Code:

#include "LedControl.h"
LedControl row1=LedControl(2,4,3,12);
LedControl row2=LedControl(5,7,6,12);

unsigned long delaytime=500;

void setup() {
  int d_row1 =row1.getDeviceCount();
  for(int address=0;address<d_row1;address++) {
    row1.shutdown(address,false);
    row1.setIntensity(address,15);
    row1.clearDisplay(address);
  }

  int d_row2 =row2.getDeviceCount();
  for(int address=0;address<d_row2;address++) {
    row2.shutdown(address,false);
    row2.setIntensity(address,15);
    row2.clearDisplay(address);
  }
}

void loop() {
  int devices=row1.getDeviceCount();
  for (int i = 0; i < devices; i++){
    delay(delaytime);
    row1.setLed(i,0,0,true);
    row2.setLed(i,0,0,true);
    delay(delaytime);
    row1.setLed(i,0,0,false);
    row2.setLed(i,0,0,false);
  }
}

EDIT
I just noticed something, there is no data going to the last 4 matrices. The timings of the blinking of the LEDs on last 4 matrices does not ties correctly (500ms) but it is in fact 250ms (i.e. half time). It means the blinks on last 4 matrices are between pulses of the first 4 matrices.

Looking at your library source, it seems the number of devices is clamped at 8. This isn't a hard limit imposed by the chip but rather practical design. SPI, especially at high speeds, can get unreliable when the bus capacitance, related to the cable lengths, gets so high that signals are skewed beyond recognition. Also the buffer in the library used to hold the row data is 64 bytes in size, intended to hold the data for 8 devices with 8 rows each.

You can edit the library to make it support 12 devices though it will require attention to detail like, increasing the buffer to 96 bytes, getting rid of short-circuits within the methods that make sure that no more than 8 devices can be addressed, for-loops, etc.


My device doesn't recognize my Arduino I'm planing to use the ESP8266 to create a web server as a start. My set up is: Arduino nano- Esp8266- Logic level converter  as shown in the diagram.

After I connected everything my device doesn’t recognize the Arudion’s USB serial port, but when I disconnect everything from the breadboard and connect the Arduino alone it show up as COM3 and when I put the circuit back again and hock up the USB to my device it no longer show up.
I’m having the issue on both win 10 and mac.
Whenever I connected the usb cable to my computer the ESP8266 flashes a light for ones.

The Nano cannot power the ESP8266. It has an absolute maximum limit of about 50mA from the 3.3V pin, since it is provided by the USB interface chip. By drawing too much current (the ESP8266 needs hundreds of mA) the USB chip stops functioning.

You need an external 3.3V regulator to power the ESP8266.


What will happen if I keep my arduino on for 24 hours? Please tell me that if I keep my arduino uno on for 24 hours with a adapter, will it get harmed?

I have several home-brUnos and a genuine Mega 2560 that are now, or have, run 24/7 for periods of weeks to months, powered by either a USB port or a USB-type wall charger. All of them supported (or still do) a string of 2 or 3 DS18b20 digital thermo sensors and a WiFi or Bluetooth radio. None of them slept during those jobs and they all still live and continue work as well as they always have.


Arduino Micro Println prints 0 I am having troubles with my arduino micro.
In my programming, I am using the serial. When I use println, nothing shows up in the serial monitor except for 0. So if I type 1, I get back 0 instead of 1, same goes for 3241234 or any random number.
Here is the code:

void setup() {
  Serial.begin(9600); //Connect to the serial monitor console
}

void loop() {
    while (Serial.available() == 0); //Wait until Serial is available

    //Read val
    int val = Serial.read() - '0'; //Val that represents input
    delay(500);
    Serial.println(val);
}

So I have another problem and people have asked for the code. Basically, printing a string returns 0.

 void setup() {
  Serial.begin(9600); //Connect to the serial monitor console
}

void loop() {
    while (Serial.available() == 0); //Wait until Serial is available

    //Read val
    int val = Serial.read(); //Val that represents input

    delay(1000);
    if (val == 1) {
      Serial.print('Firing the motor');
    } else {
      Serial.print('Please press 1 to fire the motor.');
    }

    delay(4000);
}

Instead of printing Please press 1 to fire the motor, I get 0 in the console.

Thanks for the help!

Try without

- '0'

You read your data and save into in int. then print that int, when you pass only the int, you get the int as an ASCII-encoded decimal.
Why r u doing

- '0'

?


Weird OneWire bus problem I have two DS18B20 temperature sensors connected via a OneWire bus to an arduino. I noticed that these sensors get hot, when permanently powered and decided to just turn them on for measurment.

First attempt: Define a pin as output and feed the sensors. Because I received only one value (first sensor on bus), I assumed that the current delivered may not be high enough and utilized a transistor (+resistor) as switch for the main 5V line to feed the sensors from the mains (as before). The result is the same. I only get the value of the first sensor. When I connect the sensors directly, I get both values.

I tried up to 4 seconds delay after switching the bus on and again after reading the values (before switching the bus off again), with no luck. Only the first sensor answers.

Do I have a timing or a current problem here?

UPDATE

Wiring (working): Two DS18B20 in parrallel with a 4,7k resisor between DATA and VIN. One Arduino pin used, Sensors directly powered by power-supply (same as arduino)

Wiring (not working): Broke the VIN line and added a transistor as switch between power-supply and sensors VIN. Used a second pin and a resistor to power up the line.

The transistor is a TC124E (npn) logic level transistor. I have the feeling, that this boy is not providing enough current to the sensors, which in addidtion have five meter cables attached...

UPDATE II
It is not the current. I replaced the transistor with a mosfet (70T03H) and the result is exactly the same: When switched, only one sensor answers . When I connect the gate directly to a +5V line, I get both values as expected.

Kinda think, that the switching of the pin irritates the bus or the specific device.

UPDATE III (Solution)

I tracked this down to a mixture of

Different resolution settings on the sensors
my code not waiting long enough to get the sensor with the higher resolution to setup (on-to-read time). Giving the bus slightly more time to setup before any reading is accepted, solved my problem.

If you were trying to wire your bus in parasitic mode, here is what I am using:

OneWire Bus in parasitic mode:

+------------+     +5v            +---------+     +---------+
|    MCU     |      |             | DS18b20 |     | DS18b20 |
|            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
| Strong-    |      |             +-o--o--o-+     +-o--o--o-+
| Pullup   > o------o               |  |  |         |  |  |
|            |      |               +--|--+         +--|--+
|            |      |               |  |            |  |
|    Data <> o------o---------------|--o------------|--o------ - - -
|            |                      |               |
+------------+                      V               V

I run at least three sensors this way on an approximately 6 meter bus, completely reliably.


Arduino relay module working in a wrong way I have an Arduino Mega and a 4-channel relay module.

This is the relay module.

When the Arduino digital output is LOW, the relay is energized.  When the Arduino output is HIGH, the relay coil is de-energized.

How can I fix this?

That's how they're designed to work energized is LOW de-energized is HIGH you just need to take this into account when writing your Arduino code


ATTiny85 won't boot if PIN2 is not pulled high I had some problem setting up a working ATTiny85 outside of its development board.Connection on my breadboard:
pulled high (10K R)  -- 1  PIN 8  -- VCC (+5V)
     trouble here!!  -- 2  PIN 7  --
                     -- 3  PIN 6  -- LED
               GND   -- 4  PIN 5  --

as you can guess pins are referred to actual chip's pins enumeration.My simple test code:
void setup() {
  pinMode(1, OUTPUT);
}
void loop() {
  if (analogRead(A1) > 512) {
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
  } else {
    digitalWrite(1, HIGH);
    delay(1000);
    digitalWrite(1, LOW);
    delay(1000);
  }
}

I'm using Arduino IDE v1.8.13 with digistump avrboards v1.6.7.
I flashed t85_default micronucleus v2.5 bootloader in my chip with fuses set to lfuse:0xe1, hfuse:0xdd, efuse:0xfe.The problem is that if I power the chip with PIN2 not pulled high it won't start execution of the code, it won't blink.  If it’s started from pulled high, it will start code about 5s after power on. If it’s started pulled low code won’t execute until is pulled high. As I pull high, even just for a second, PIN2 it will start blinking and executing code.
Is it normal? I think I have missed something.

Well, I've made some headway.  I hope to update this with something more helpful though.
I don't have a digispark or even the correct Zener diodes to replicate the necessary parts of it.  However, I did install t85_default.hex on an ATTiny85 with some alterations to the hex file to place break instructions in a few strategic places.  And then I ran avarice/debugwire against it.
The basic problem is that it's trying to tune the internal oscillator against the USB frames by looking at the D- pin.  Basically, it's stuck in tuneOsccal.
988  00001d06 <tuneOsccal>:
   1     1d06:       b3 9b           sbis    0x16, 3 ; 22
   2     1d08:       fe cf           rjmp    .-4             ; 0x1d06 <tuneOsccal>
   3     1d0a:       07 d0           rcall   .+14            ; 0x1d1a <countFrame>
...

So if you want to avoid this, you need to compile with that feature off, and there is a feature to do that.
I have not yet run one with this feature disabled.  But I did compile t85_default once, using make CONFIG=t85_default and found it necessary to remove the START_WITHOUT_PULLUP from the first line of the t85_default/bootloaderconfig.h file.
The code mentions the existence of OSCCAL_SAVE_CALIB, which lets you specify your own OSCCAL value, assuming the factory one for the chip isn't good enough for whatever reason.  But there doesn't seem to be any guidance on how you're supposed store it or where.  Looking at the code though, if enabled, you can see it loads the OSCCAL value from just before where the bootloader starts.
A simple way to put it there without messing with command-lines and linker scripts would be to just edit the the t85_default.hex that results from building with OSCCAL_SAVE_CALIB enabled, and add an extra record for setting the osccal value at the correct address, which I guess would be 0x19FA, so:
:0119FA00XXSS
Where XX is whatever you've determined your OSCCAL value is and SS is the checksum value, or 0x100 - ((0x14 + XX) & 0xFF) in this case.  Or, if you want to be lazy, put whatever you want for SS and let AVRDude complain tell you what it's supposed to be when it tries to load the .hex file.  It will report the expected value in decimal, which you can convert to hex and patch into the file, and run AVRDude again.


Arduino stopwatch, which board to use? I am planning on making a simple stopwatch with:

A display
One or two additional buttons to start the stopwatch and stop the stopwatch and
maybe reset it.

The problem is that it has to be as small as possible.
With all those different Arduino boards out there, I don't know which one I should buy (mini, micro, nano, ...).

I am not sure how many pins I need for the LCD since I have read that in fact not all pins are mandatory for the LCD. I have done something earlier with an LCD and I found the pot meter for the LCD contrast level a bit of waste of space. Could I just replace it with a certain resistor or something?

How many pins in the end would I need and which board would be fitting for this little project?

By that photo you posted, you pretty much answered a decent part of your question. You'll need six pins for the LCD, and one or two for the button. That means that you need a total of 8 pins. That Uno pictured has 20 (analog can act as digital, too).

As far as the boards, if you feel comfortable with some extra work, I'd recommend an ATtiny. From what I can find, it seems like you can drive a LCD with a 44 or an 84 (similar, but the 84 is more powerful).

Source for image and how to program chip. I'm not going to go into the details for this method, as the link has the necessary files...

That's the smallest way to do this*, however, if you want to use a real Arduino board, then I'd recommend the Micro for a few reasons.

First of all, it has the newer ATMEGA32u4 chip, found on the Leonardo. I do not recommend the Mini because, although it's the smallest of the three, it doesn't feature on board USB. You would have to buy another adapter to program it. If you're already using a breadboard, the extra 2cm (or so) is worth not having to spend more to buy both of those components. The Nano is the equivalent of the Mini, only with USB. Also, the Nano and the Micro are roughly the same size, one a little bit longer and one a little bit wider.

However, the Nano and Micro are roughly the same as far as processing power, so I'd recommend that, if you can get one significantly cheaper, to go with that. It doesn't really matter that much.

*If you're building this on a breadboard, it won't be smaller. If you're transferring to a PCB, then you should use an ATtiny.

As far as the pot goes, I'd recommend getting a trimmer with an equivalent value. Some of them are very small, as I have one that fits on the USB connector part of my thumb drive. They need a screwdriver to adjust, but I would recommend it. I've had issues moving it from a dark room to in the sun and not being able to see it clearly. Spend the two cents and the 2 cm2 and have an opportunity to change it if needed.

For the battery, I would recommend any rechargeable battery (under ~3.5V) if and only if you add a proper chip to not waste energy in the conversion. I talked about this in this post.


What's the benefits between different interrupts on Arduino On an Arduino you can have several different interrupt types, two of them being RISING and FALLING. Looking past that RISING is from LOW to HIGH, and FALLING is the opposite, what are the benefits of using one or the other?

To clarify; why would you use a RISING interrupt or a FALLING interrupt?

Imagine that you have the circuit below:

simulate this circuit – Schematic created using CircuitLab

Let's say that you wanted to catch the user pressing the button. The input signal will go from high to low, which is a falling edge. So you would use a FALLING interrupt to catch this event. Easy, right?

Now let's say you wanted to catch a user releasing the button instead. This time the inverse is true, so you want to use a RISING interrupt.

You should note that since these interrupts are edge triggered, the simple circuit below would not be ideal. Without any debouncing, there may be several edges to trigger from, resulting in repeated interrupts. Also, given the analogue nature of the design, we can't be sure that the rise / fall times will be fast enough to trigger the edge interrupt. We can get around this by adding a 100nF capacitor across the switch and following by a Schmitt trigger (which I can't find a symbol for in the circuit editor!).

So to answer your question, you use the interrupt that is correct for the event you are trying to catch. The Arduino MCU implements both edges for completeness and flexibility in your design, so if this interrupt was coming from an external IC you have no control over the design of, you can easily match the interrupt to its behaviour without having to add in an inverter.


How to program an Arduino pro mini using native serial port (on my mainboard) How can I program my Pro Mini using the native RS232 Serial port on my Mainboard (aka com1).

Google-ing did not really help and a quick search here for "pro mini programming com1" did not deliver any results.

I already have a MAX232 module connected between the Pro Mini and the PC.

I have already tested the com1 port for function by sending stuff to an Arduino mega via its usb-to-serial port and echo-ing that to com1.

Which succeeded (at least sort-of [receiving some random clutter in between characters or missing some characters at all])

I did try the obvious (i.e. selecting pro mini from the board menu and then selecting the com1 port and hit upload).

But that did just produce a timeout-error…

An Option to set the programmer to simple Serial Connection or something similar does not exist to my knowledge (well it does but only if we're talking about STM32 based boards like the blue pill).

To upload a hex file to Arduino over Serial interface, the bootloader must be active. The bootloader is active after reset. It waits a short time if a new application is uploaded. If not, it jumps to existing application.

To reset the MCU on Arduino boards with independent USB chip a circuit connected to DTR line of serial is used.

On a board like the Pro Mini there is no chip for USB neither an auto reset circuit. You must reset the board with the reset button right before avrdude sends the hex file. avrdude tries ten times, so you have 10 chances to time it right after you hit the Upload button.

Some USB-to-TTL-Serial adapters (or RS232 adapters) have the DTR line and it can be used to reset the board.

Or use ISP flashing over the ICSP header with a programmer or other board as programmer.


Current available SRAM? I've reached the limit on available SRAM memory. I need to "cut down" some variables, but I actually don't know how far I need to go with it.

Is there a way on measuring current available memory on program execution?

If you set "Show verbose output during compilation" in your IDE preferences, you'll see a message like the following in the IDE window's lower pane. The part I bolded is the amount of SRAM assigned:

  Sketch uses 2,148 bytes (6%) of program storage space. Maximum is 32,256 bytes.
  Global variables use 204 bytes (9%) of dynamic memory, leaving 1,844 bytes for local variables. Maximum is 2,048 bytes.

You can also include this function and print its result to get the same information on the terminal during run-time:

int freeRAM () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}


Serial is freezing arduino I'm using a LinkIt ONE Arduino-like to send sensor data via MQTT.
It always worked very well, then out of the blue, it stopped printing anything using Serial.print();
But if I ommit the "Serial.begin(9600);" line, the code runs normally, sending sensor data via MQTT, even if I can't see debug output.
This shows the problem is on the Serial handling.
Since I can't show the entire code here, here's two test cases:
1.
void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial1.println("This came from serial 1"); //does nothing
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

It shows me the following output:

This came from serial 0
This came from serial 0
Thi

Looks like the module freezes before the third iteration.
But if I omit the lines that aren't printed, from Serial1:
2.
void setup(){
  Serial.begin(9600);
  while(!Serial);  //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  delay(1000);
}

No output is shown on Serial monitor.
What is the reason behind this? Since Serial1 prints nothing, why can't I remove it?
Observations:
I tested the code in two LinkIt ONE modules of the same model.
I tested it in Arduino SDK 1.6.8, 1.5.6r2 and 1.6.5.
Edit:
Just made another test using the code below. It blinked two times showing that
Serial.begin(9600); runs
while(!Serial); runs (it didn't freeze the module waiting for Serial to initialize)
But Serial.println(); freezes
void setup(){
  pinMode(13, OUTPUT);
  blink();
  Serial.begin(9600);
  blink();
  while(!Serial); //Wait until Serial is ready before printing
}

void loop() {
  Serial.println("This came from serial 0");  //works
  blink();
  delay(1000);
}

void blink(){
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);
}

The problem was solved by:

making a clean install of Arduino IDE 1.6.9
uploading the LinkIt SDK on board manager from version 1.1.17 to 1.1.23.

Then the Serial function returned back to normal.


Questions Concerning Arduino Compatible Boards I've seen an Arduino-compatible board called Bluno from DFRobot. I'm curious if a shield, specifically the DFRobot motor shield can be connected to the Bluno.

Can anyone confirm if it can be connected with a shield?

The Bluno is identical to the Uno, except the USB-to-serial chip, also supports BT. So it won't be a problem.


Arduino Mega PWM - 100ms Period - SSR and Heater I'm not very advanced in Arduino "core" functions, so I need your help.

I'm using a Solid State Relay in order to control a heating element, with a PID Library (PID_v1.h) to obtain the OUTPUT of the PWM.

The code itself is not a problem, so that I'll not post it here.

Summarizing, this is the code where I send the PWM to the Relay:
    analogWrite(RELAY_OUT, outputValue);

I've found in this article that:
"The analogWrite function is used to set the duty cycle of a PWM pulse train that operates at approximately 500 Hz. Thus, with a frequency = 500 Hz, the period is = 2 ms."

My concern is that the response time of the relay (FOTEK SSR-60 DA) is 10ms (to turn on or to turn off), but I DO NOT KNOW how to configure Arduino PWM to work accordingly to this Relay, in a period greater than 10ms.

I've found in some pages some people changing the clock frequency in order to have a "fast pwm", but I need to know what values I have to use to get a "slow pwm", for a period greater then 10ms.

Can you help me with that? I've been searching a lot for this answer, but I could not find any "definitive"answer.

Thank you in advance!

Everton

I'd suggest using the TimerOne library.

Call Timer1.initialize(10000) in setup.
Then call Timer1.pwm(pin, duty); in your loop. Where pin is 11, 12, or 13 for the MEGA, and duty is between 0 and 1023.


MPU9150 (JEFF LIB) + FIFO_OVERFLOW INTERRUPT + SERIAL PRINT Overflow enthusiasts!

I am trying to log accelerometer and gyro data using Serial.print. I have enabled the FIFO_Overflow interrupt. Whenever I log data, the serial port freezes. I am suspecting an interrupt issue while I am using Serial.print. Is there any way to get continuous data for debugging purposes? I know that the Serial library can affect interrupts and wonder whether you guys could help me a little bit ?

#include "Wire.h"
#include "I2Cdev.h"
#include "MPU9150.h"
#include "helper_3dmath.h"

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for InvenSense evaluation board)
// AD0 high = 0x69
MPU9150 accelGyroMag;
#define LED_PIN 13
volatile boolean state_fifo_int = false;
uint16_t fifo_count;
uint8_t fifo_buffer[8];
int16_t acc_temp[3];
int16_t gyro_x;

void setup(){
    // join I2C bus (I2Cdev library doesn't do this automatically)
    Wire.begin();
    // initialize serial communication
    // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
    // it's really up to you depending on your project)
    Serial.begin(115200);
    // initialize device
    Serial.println("Initializing I2C devices...");
    accelGyroMag.initialize();
    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(accelGyroMag.testConnection() ? "MPU9150 connection successful" : "MPU9150 connection failed");
    // configure Arduino LED for
    pinMode(LED_PIN, OUTPUT);
    attachInterrupt(0,fifo_int,CHANGE);
}

void fifo_int() {
  state_fifo_int = true;
}

void loop(){
  while(!state_fifo_int) {
    accelGyroMag.setIntFIFOBufferOverflowEnabled(true);
    // enable fifo_interrupt
    accelGyroMag.setFIFOEnabled(true);
    accelGyroMag.setAccelFIFOEnabled(true);
    accelGyroMag.getXGyroFIFOEnabled();
    accelGyroMag.getAccelFIFOEnabled();
    fifo_count = accelGyroMag.getFIFOCount();
    accelGyroMag.getFIFOBytes(fifo_buffer,8); // fill in fifo bytes
    acc_temp[0] = (((int16_t)fifo_buffer[0]) << 8) | fifo_buffer[1];
    acc_temp[1] = (((int16_t)fifo_buffer[2]) << 8) | fifo_buffer[3];
    acc_temp[2] = (((int16_t)fifo_buffer[4]) << 8) | fifo_buffer[5];
    gyro_x = (((int16_t)fifo_buffer[6]) << 8) | fifo_buffer[7];
    Serial.print((float)acc_temp[0]/16384);
    Serial.print("  ");
    Serial.print((float)acc_temp[1]/16384);
    Serial.print(" ");
    Serial.print((float)acc_temp[2]/16384);
    Serial.print(" ");
    Serial.println(gyro_x);
   }
   accelGyroMag.setIntFIFOBufferOverflowEnabled(false);
   // disable fifo_interrupt
   accelGyroMag.resetFIFO();
   state_fifo_int = false;
}

The library for the MPU9150 is by Jeff Rowberg.

When I've gotten into a bind with data being generated faster than I can dump it, or the process cannot tolerate the printing delays, I've made a memory buffer to store as much raw data as I can and print it after the test-run. If you're not using a debugger (which can print memory contents), you'll still need to have serial print code in your sketch but it can execute after the you run the code under test. Store the minimum size raw data (to maximize the amount you can store) and do the formatting on your PC.
If you need to be able see what happened prior to an unusual event your code can detect, use a ring buffer (FIFO) in memory and let it wrap around (don't even bother to detect wrap-around). As soon as your code detects the event, print the ring-buffer contents.
It's not continuous capture but often, it's enough.


What to use instead of a USB to serial converter The usb to serial converter i found was $4 .maybe i could use something less expensive,like jus a port.I need serious help ,the serial port was about $1

May I suggest RS232 connection? It is an ancient tech but it might work for you. I am adding a tutorial. Also a component from eBay, which is 0.99 US dolar.


Avrdude fails at specific baudrates I'm seeing something very strange. If I run:

ard-reset-arduino /dev/ttyACM0;
/usr/share/arduino/hardware/tools/avr/bin/avrdude -C/usr/share/arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:`pwd`/.build/main.ino.hex:i;

Avrdude uploads my sketch to an Arduino Uno just fine. However, if I change the buadrate to 57600, it fails with the error:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I've tried manually pressing the Arduino's reset button just before I upload, but there's no change.

Why is this happening? If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

If I change it back to 115200 baud, it uploads fine...even though the sketch itself initializes the serial port to 57600.

The bootloader is a piece of code designed to work at a specific baud rate. As KIIV said in his answer only the USB-based Arduinos would be relatively immune to changing the rate.

What your own code does, after being uploaded, is completely irrelevant.

  Avrdude fails at specific baudrates

Your title really should be: "Avrdude only works at one baudrate (the one it was designed to use for a specific board)"


how can i achieve a TTL pulses with duration of 1ns and what board do I need Hi I need to supply TTL pulses to my driver to get a 1ns pulse with 20KHz.

Is that possible with Arduino? what is the board and setting I need?

thanks

You can create narrow pulses from the 20 kHz rising edge, maybe down to a few ns, and occurring a few ns after the rising edge, with a couple of logic parts,by taking advantage of their propagation delays.  Say 74AHC04 and 74AHC08.

http://www.ti.com/lit/ds/symlink/sn74ahc04.pdf

http://www.ti.com/lit/ds/symlink/sn74ahc08.pdf

You can investigate other logic families to see it there is anything faster.

20 kHz = 50 µs period, you can create that with an Uno using the micros() times.

Something like this in loop:

void loop() {
  oldTime = micros();
  while (1) { // avoids jitter from the loop behind the scene actions
    timeNow = micros();
    if ((timeNow - oldTime) >= halfPeriod) {
      PINB = PINB | 0b00000001; // toggle D8 by writing a 1 to the Input port
      oldTime = timeNow;
    } // end time check
  } // end while
} // end loop

Check the timing with a scope, might have to shorten halfPeriod a little to allow for the time checking and the port manipulation.


Arduino Leonardo - Setting up bluetooth - AT command from terminal does not return anything I am trying to setup bluetooth with a board that contains Arduino Leonardo chip.
My full setup is:
The main board: https://www.dfrobot.com/product-1148.html
The base shield: https://coolcomponents.co.uk/products/grove-base-shield-for-arduino-v2
The bluetooth module: https://wiki.seeedstudio.com/Grove-Serial_Bluetooth_v3.0/
The bluetooth module is connected to D8 port of the base shield.
The reason is "not all pins on the Leonardo and Micro support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI)." as explained here: https://www.arduino.cc/en/Reference/SoftwareSerial
Here is the full code.
#include <SoftwareSerial.h>   //Software Serial Port

/*Connect your Bluetooth Module to D8 otherwise it will not work due to Arduino Leonardo */

#define RxD         8
#define TxD         9

SoftwareSerial blue(RxD,TxD);

void setup()
{
    Serial.begin(9600);
    blue.begin(9600); //anything other than 9600 will not work

    // wait for serial port to connect. Needed for native USB
    while(!Serial){
    ;
    }

    pinMode(RxD, INPUT);
    pinMode(TxD, OUTPUT);

    Serial.print("Started\n");
    setupBlueToothConnection();

}

void loop() {
char recvChar;
    while(1)
    {
        if(blue.available())
        {//check if there's any data sent from the remote bluetooth shield
            recvChar = blue.read();
            Serial.print(recvChar);

        }
        if(Serial.available())
        {//check if there's any data sent from t he local serial terminal, you can add the other applications here
            recvChar  = Serial.read();
            blue.print(recvChar);
            delay(400);
        }
    }
}

void setupBlueToothConnection()
{
  //blue.begin(9600);

  blue.print("AT");
  delay(400);

  blue.print("AT+ROLES");  // set the role as slave
  delay(400);

  blue.print("AT+NAMESlave");   // set the bluetooth name as "Slave" ,the length of bluetooth name must less than 12 characters.
  delay(400);

  blue.print("AT+AUTH1");
  delay(400);
  blue.flush();
}

The output from the Serial Monitor (set as BOTH NL & CR, 9600) as follows:
Started
OKOK+Set:SOK+Set:SlaveOK+Set:1

The problem is when I send AT commands from terminal I get nothing in return.
However if I send AT command from the IDE, I am getting feedback from the bluetooth.

The issue is fixed.
Note: This is the version includes Serial1 rather than SoftwareSerial. The rest is the same.
Serial.read()

Returns the first byte of incoming serial data available.

So, when I send AT command from terminal, it does send "A" and then "T" rather than "AT" as a string which Bluetooth expects as stated in the product's documentation:

AT Command format: Uppercase AT command format. string format, without any other symbol. (e.g. \r or \n).

Hence, I have added the following function:
String SerialString() {   // Function to generate string from chars sent via Serial Monitor

  String inputString = "";  // to hold the string

  while (Serial.available()) {

    char inputChar = (char)Serial.read(); // get the new byte:
    inputString += inputChar;             // add it to the inputString:
    }

    return inputString;     // returns completed string
}

Then inside void loop():
String WholeCommand = "";
if(Serial.available() > 0){
    WholeCommand = SerialString();
    Serial1.print(WholeCommand);
  }

Now, when I send AT from Serial Monitor, I can get OK from Bluetooth.


May I use both USB-serial and tx/rx pins at the same time? I am building a CNC machine based on GRBL code on a uno. I also have found a script to read data on a N64 controller. I know there is not enough pins available to do both codes running on the same arduino, so I was wondering if I could have my GRBL arduino connected to a computer thru USB, and at the same time, have a second arduino reading data from the n64 joystick, create Gcode accordingly, and feed that Gcode to the GRBL arduino through the tx/rx pins of each of them.
I guess I'll have to put a on-off switch on the tx/rx wife to avoid "noise" when I actually send Gcode to the GRBL arduino from the computer.

Does this all make sense?

The usb port and the tx/rx pins are one and the same thing. You can't use one thing for two jobs at the same time. So you will either have to implement some kind of multiplexing system (switches) or come up with a different way of doing things, maybe using the SoftwareSerial library or the Wire Library or investing in a better board with more than one serial port.


Why can't the OCR1A register be set to 1 to get a 8MHz PWM? The max PWM frequency that can be achieved with an Arduino is by using the PWM fast mode with the pre-scaler set at 1 and the TOP counter value at 3, getting 4MHz

f_OC = 16000000/(1(1 + 3)) = 4000000

Why can't be the TOP value set at 1?

Because then you only have 1-bit PWM. And there aren't an awful lot of applications for 1-bit PWM.


Arduino long distance cable tester We have a 50 pair cable running about 1.5-2 KM with some services running on different pairs. One pair has recently become intermittent and is losing connection for 1-2 seconds at random. It might happen a few times an hour, so I jumped the service onto another pair. There is a modem connected to the pair for communication between two sites.

When resistance tested with a multi meter with a loop in one end it was reading 330 Ohms. When using an oscar meter it was reading -2.4db which is the same readings for other pairs.

I would like to use an Arduino to monitor the line resistance for a few days and see if there are any spikes or breaks in the line. I was going to use an analog input as a multimeter by using a known resistor and the looped pair as the other resistor.

Does anybody think this will not work?

How else could I go about this?

Sure, no reason that wouldn't work. For best results you want a known resistor of about the same resistance as, or a little below, the one you are measuring.

However, if what you are seeing is an actual open circuit then there's little benefit to measuring the resistance - you may as well just treat it as a switch or button, give it a large pullup, and use a digital input (or even an interrupt) to give a simple "OK / ERROR" signal.


How can I use a BlueSMIRF Silver (RN-42) as a HID Keyboard (on IOS)? I've got a BlueSMIRF Silver (RN-42) Bluetooth module.
I am trying to create a basic keyboard I can play with on an iPad Air.

At the moment barely manage to get the module to pair with OSX
but only through using Bluetooth Setup Assistant and using "Passcode Options...use a specific code".

With this option, the module pairs, but the connection resets about every 5 seconds.

On iPad it tries to use a generate number really fast and fails straight away, being unable to connect.

I noticed there is a BlueSMIRF HID version, but from what I can tell, the hardware is the same,
just the firmware is different. I've gone through the whole Bluetooth Data Module Command Reference & Advanced Information User’s Guide(pdf link) manual and from what I can gather,
even though I have Silver firmware burned onto my module, I should be able to set and use the HID profile
(from the default SPP):

  Roving Networks modules shipped with firmware version 6.11 and higher
  support the HID profile. You do not need special firmware if your
  module is running firmware 6.11 or higher.

and my module reports version as:

Ver 6.15 04/26/2013
(c) Roving Networks

I've also gone through the Bluetooth HID Profile(pdf link) guide from Roving Networks, but the same information is present in Chapter 5 of the advanced user's guide mentioned above.

I've setup the following settings (with commands used):

HID Profile (S~,6)
Device discovery and pairing is set to automatic, without using GPIO6(SM,6)
HID Flag is set to Keyboard (SH,0000)
Authentication is set to open (SA,0)

I've also tried the inquiry scan(SI,0800)  and page scan(SJ,0800)  windows to maximum
in the hope it would increase the odds of successful pairing and made sure I rebooted the module and checked the settings again.

I have used the same module with the SPP profile just fine, but I'm still fairly new to Bluetooth
and this is the first time I try to use the HID profile.

How can I use the BlueSMIRF Silver as a basic Bluetooth Keyboard for an iPad Air ?

I should be able to set and use the HID profile (from the default SPP)

Unfortunately, your assumption is incorrect. From the same documentation you quoted, the previous sentence says:

  To use Roving Networks’ Bluetooth HID profile, you must use a special
  build of firmware, version 6.03 or later.

Poorly phrased, this does mean that you need to have two things:

A special HID firmware
Version 6.03 or later

Your BlueSmirf Silver only complies with the second condition; it does not have the special HID firmware (also note that the Rovnix command reference does not address a specific variant of the BlueSmirf, but speaks generally about all of the variants).

The SPP protocol (Serial Port Profile) is used for emulating a serial cable, and functions as a substitute for the physical RS-232 connection, but cannot stack pure HID profile on top of it. In order for you do talk HID, you will need the HID firmware.

As a side note, the HID version comes with SPP and you can switch between the two modes interchangeably, I have been using the HID version for a while now and it works fine (including the pairing with iOS).

Another misfortune is that it does not appear that Roving Networks officially support any re-flashing of the BlueSmirf firmware, so unless you are willing to reverse the hardware, this is off the table as well.


Doesn't work radio transmission from Arduino Uno to Arduino Pro Micro I have Arduino Uno, Arduino Pro Micro, XY-MK-5V and FS1000A.
I need transmit data from Pro Micro to Uno.

Transmitter:

    #include <VirtualWire.h>

    void setup() {

      Serial.begin(9600);

      vw_setup(2000);
      vw_set_tx_pin(14);
    }

    void loop() {

      send("Test message!");
      delay(2000);
    }

    void send (char *message)
    {
      vw_send((uint8_t *)message, strlen(message));
      vw_wait_tx();
    }

Receiver:

#include <VirtualWire.h>

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

    vw_set_rx_pin(12);
    vw_setup(2000);

    vw_rx_start();
}

void loop()
{
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;

    if(vw_get_message(buf, &buflen))
    {
        for(int i = 0; i < buflen; i++)
        {
            Serial.print(buf[i]);
        }

        Serial.println();
    }
}

I dont know why it's doesn't works. When I changed Uno with Micro and Micro with Uno, it's worked.

But I need: Micro + transmitter FS1000A & Uno + receiver XY-MK-5V.

Please help me. I'm using this Pro Micro.

Thanks for your answers. I solved this problem, my Chinese copy has problems with power.


Confusion in the use of byte variable A byte stores an 8-bit unsigned number, from 0 to 255.

I can understand the following line:

byte b = B10010;  // "B" is the binary formatter (B10010 = 18 decimal)

But I also saw a use such as:

volatile byte state = LOW;

What does the last line mean here? Is that special for Arduino?
I mean LOW is not a 8 bit unsigned number. LOW is not a number here.

There is probably somewhere else, like this:

#define LOW 0

Which means the pre-processor turns your line from this:

volatile byte state = LOW;

into this:

volatile byte state = 0;

There is nothing arduino-specific here, just the use of standard C/C++ features.


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

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


Does the Arduino Yun have to be powered exactly at 5V? I'm working on a senior project and I am using a ATX PSU to supply power to the Arduino Yun and other components. If I'm not mistaken, its powered through the usb. I took a usb cord, strip the sheath and put the proper connections on the breadboard and connected the red wire from the PSU to the breadboard as well. When I measure it, the voltage is 5.1V max. I'm scared to hook it up to the Arduino since I read that if its above 5, it will fry it. Is this voltage fine? If not, will I have to put resistors on it to get it down?

It is fine. That is only 2% too high. The microcontroller is the ATmega32U4 and it can have 5.5V. The wifi module runs at 3.3V, and it has a voltage regulator. Some voltage is also lost in the cable. If the voltage is 6V, then you are in the danger zone, but not with 5.1V.

There are clones and shields of the Arduino Yún. Each has its own power supply demands. You should read what the specifications are for your board. The official Yún board requires 5V from the USB cable or 5V at the VIN pin.


stk500 getsync() attempt 10 of 10 atmega328pu I've been getting this very common error on my atmega328pu circuit.

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x83

Some things iv'e tried are:

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

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

The first thing you should do is add a 0.1uF capacitor connected "in series" with the jumper wire from the DTR terminal of the FTDI programmer to pin 1 of the Atmega328P-PU chip. For most people, this will solve the problem.

I see you also have a "push button reset switch". If you can press/release this button at precisely the right moment, the sketch should upload without error. Using the Arduino IDE, if you click on the "Upload" button then press and release the "push button reset switch" just after the Arduino IDE's black console window shows you the line starting with:

  Sketch uses x bytes (y%) of program storage space...

there is a good chance it will work. You can try holding the "push button reset switch" down for 1 to 1.5 seconds.

Please add a capacitor to the DTR circuit or disconnect it from the Atmega328P-PU before you go any further. A DTR connection to the programmer is not needed for the "push button reset switch" method of uploading and a "direct, hard wired connection" could cause an issue.


Reading a .csv file element wise I'm fairly new to arduino programming and C/C++. I would like to read a .csv file element wise, and send each element via. a nRF24L01 tranceiver to a raspberry pi. Right now I'm able to read the .csv file with Serial.write(<file>.read()). I was wondering if there's a way to read each element one at a time, if so how would i do that?

My thoughts (Pseudo code-ish):

loop through every element in .csv file {
    save the current element to X.
    send X to raspberry pi (I already have a function for sending)
}

I hope someone can help. Thanks in advance.

The read() method works character-wise, not element-wise. Then you
have to rethink your algorithm to loop over characters:

store each character in a buffer
send the whole buffer (i.e. a single element) when you see a delimiter

Example:

const size_t BUFFER_SZ = ...;
char buffer[BUFFER_SZ];
size_t pos = 0;    // current write position in buffer
int c;

// While we can read a character:
while ((c = <file>.read()) != -1) {

    // If we get a delimiter, then we have a complete element.
    if (c == ',' || c == '\n') {
        buffer[pos] = '\0';         // terminate the string
        raspberry.println(buffer);  // send to the RPi
        pos = 0;                    // ready for next element
    }

    // Otherwise, store the character in the buffer.
    else if (pos < BUFFER_SZ-1) {
        buffer[pos++] = c;
    }
}

Here the buffer is sent as a string. If you want to parse it into a
number, you can use sscanf.

This code assumes Unix text-file conventions, i.e. each line of the file
(including the last one) being terminated by an LF character. You may
have to adapt if your file is different.


There are several possibilities.

Arduino GPIO pins drive outputs to ground or 5V.

The pins on the Nokia 5110 LCDs boards I have are not 5V tolerant. So you might have damaged them when the Arduino's GPIO connected to 5V.

A simple fix is to put a 10k ohm resistor in each signal path, i.e.

sce -- pin 7
rst -- pin 6
d/c -- pin 5
DN -- pin 4
sclk -- pin 8

You could get a level-shift chip, or build a circuit, but resistors are quick, cheap and easy.

I would strongly recommend using a very simple Arduino library to get the display working. Then, once everything is working, continue with your current approach. All you need is a simple test; something which turns pixels on and off to check that it works.

I have had good results with the Arduino Playground Philips PCD8544 (Nokia 3310) driver

I have several Nokia 5110's. A few needed the values loaded at initialisation to be tweaked, to make the display visible.

Specifically in void LcdInitialise(void):

  LcdWrite(LCD_C, 0x21 );  // LCD Extended Commands.
  LcdWrite(LCD_C, 0xB1 );  // Set LCD Vop (Contrast).
  LcdWrite(LCD_C, 0x04 );  // Set Temp coefficent. //0x04
  LcdWrite(LCD_C, 0x14 );  // LCD bias mode 1:48. //0x13
  LcdWrite(LCD_C, 0x20 );  // LCD Basic Commands
  LcdWrite(LCD_C, 0x0C );  // LCD in normal mode.

I have had to tweak Set Temp coefficent, LCD bias mode 1:48 and Set LCD Vop (Contrast) to get make the display clear, without looking washed-out, or all-dark. Using a very simple library like the Philips PCD8544 (Nokia 3310) driver should make it easy to adjust this until things work well.


Connection bluetooth master and slave with Android I send a date from my android to arduino without problem, but also i want send date from arduino to android later of received the date from android.

I have time trying it, but i can not yet, help me.
My codec of arduino

char enter;
#include <SoftwareSerial.h>
SoftwareSerial conect(10,11);

void setup()
{
 pinMode(8,OUTPUT);
 conect.begin(9600);
 digitalWrite(8,LOW);
}

void loop()
{
 if(conect.available()>0)
  {
   enter=conect.read();
   if(entrada=='1')
   {
    digitalWrite(8,HIGH);
    conect.print("1");
   }
 }
}

And in the side from android this is my handler for drive the the date that arrive.

 Handler mhandler=new Handler(){
    @Override
    public void handleMessage(Message msg)
    {
        super.handleMessage(msg);
        switch (msg.what)
        {
            case CONECTADO:
                //ManejarDatos msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                msjre = new ManejarDatos((BluetoothSocket)msg.obj);
                break;
            case MENSAJELEYENDO:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf,0,msg.arg1);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
                break;
        }
    }
};

And on my class for read and write i have this

private class ManejarDatos extends Thread
{
    private final OutputStream salidadatos;
    private final BluetoothSocket sockk;
    private final InputStream entradadatos;
    public ManejarDatos(BluetoothSocket socke1)
    {
        sockk=socke1;
        OutputStream temporalsalida=null;
        InputStream temporalentrada=null;
        try
        {
            temporalentrada=socke1.getInputStream();
            temporalsalida=socke1.getOutputStream();
        }catch (IOException e){}
        salidadatos=temporalsalida;
        entradadatos=temporalentrada;
    }
    public void run()
    {
        byte[] espera;
        int esperaalmacen;
        while (true) {
            try {
                espera=new byte [1024];
                esperaalmacen=entradadatos.read(espera);
                mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera)
                        .sendToTarget();
            }catch (IOException e){break;}
        }
    }
    public void escribe(byte[] bytes)
    {
        try {
            salidadatos.write(bytes);
            //handler.obtainMessage(MENSAJE_SALIDA,-1,-1,bytes).sendToTarget();
        }catch (IOException e){
            //Log.e(TAG, "....Error al enviar dato" + e.getMessage() + "...");
        }
    }
    public void cancel()
    {
        try{
            sockk.close();
        }catch (IOException e){}
    }

}

When i push button, send a date to arduino, here my codec of button(i send 1 for bluetooth)

        Enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String salida="1";
            msjre.escribe(salida.getBytes());
        }
    });

First try

if(conect.available()>0)
 {
enter=conect.read();
if(1)
{ digitalWrite(8,HIGH);
 conect.print("1");
}
 }
 }

If that works,  think about what entreda is and that exactly you're trying to do there.


Arduino communicating back and forth with PHP server I am researching to find the best method to work with in order to control the arduino from a web interface (hosted on a web server using PHP) and also sending data from arduino to webserver and save to mySql.

2 methods which I have found that a lot use are save the data to a text file or in the url.

Which is the best or are there any better methods?

I would suggest your best bet would be to pass messages back and forth via JSON, via Get/Post http request.

So to send data, you send a POST request (to the PHP server) with your data in JSON in the content.  To get instructions, you send a GET request to the PHP server and get a contents field with JSON in it.


Arduino Mega not recognized by device manager My lab partner and I are working on a project for school and we are using an Arduino Mega 2560 for prototyping. The board was working just fine until, out of nowhere, the board was not being recognized at all. I tried reinstalling the IDE but still it does not work. I checked to see if the Arduino driver was installed, but the board does not show up in the device manager. Also, the L LED on the board does not light up at all. Attached are photos to help understand the problem.

If someone could help, it would be much appreciated. Thanks.

hey i had the same problem, i am thinking because i installed atmel studio and then this started happening,
I then downloaded arduino from the microsoft store,(no change)
then i restarted the pc, now its compiling and uploaded normally but still does not show the name of the board that is connected just shows lets say just  COM22 with out saying what board


won't verify a simple code When I tried to verify a simple “Hello world” program I get the following message:

class hardwareSerial has no member named printin.

What does it mean?

Try using println instead of printin.  It stands for print line.


Use of array in case statement I want to know how I can use case statement for each array.

Below is my code:

int incomingByte = 0;

void setup()
{
  Serial.begin(115200);
  for (int thisPin = 2; thisPin < 6; thisPin++)
  {
    pinMode(thisPin, OUTPUT);
  }
}

void loop()
{
  int button1[] = {0xFF, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05};
  int button2[] = {0xFF, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06};
  int button3[] = {0xFF, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08};
  int button4[] = {0xFF, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C};

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
  }

  switch (incomingByte)
  {
    case button1:
      digitalWrite(2, HIGH);
      break;
    case button2:
      digitalWrite(3, HIGH);
      break;
    case button3:
      digitalWrite(4, HIGH);
      break;
    case button4:
      digitalWrite(5, HIGH);
      break;
    default:
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        digitalWrite(thisPin, LOW);
      }
  }
}

case doesn't work like that; it can only switch on a single integer. Are you trying to pattern-match those sequences of bytes? You'll have to use some sort of state machine instead, keeping track of what bytes you've received and where in the expected pattern you are.


avrdude: stk500_rcv :programmer is not responding I'm a newbee to Arduino programming and hoping someone can help me with this. These are the error messages.

avrdude: stk500_rcv() : programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10:not in sync:

Problem uploading to board.

I'm using a Arduino UNO clone on com port 3,the blink sketch is functioning. I get the mentioned error message on all sketches I have ran. Not sure what to do.

try this site: https://github.com/Makeblock-official/Makeblock-USB-Driver/ , it works for me. This is a driver for arduino, and command for bash


Arduino not running the sketch with external power supply of 9v, but runs the program when connected to pc Can anyone please help me figure out/ point the reason of this arduino problem? I uploaded a simple arduino sketch (blink an LED ) just to test if my real program was the reason of the "abnormality" of this board. It works fine when I connected it to PC via arduino cable, but doesn't run the program when I use an external power supply(9v) and connected it to the Vin pin of arduino.

Need help and hoping for fast replies. I will be having a competition tomorrow, this is very urgent. please guys.

for the schematic diagram, there are no other parts inserted to the arduino board, aside from the 9v battery. I was able to say that the program work on "LED blink" by observing the lights of "TX" LED on the board. please help me. :(

TX LED is blinking because of communication (indicating data transmit via serial). It will not blink if there are no communication from Arduino through USB cable.

For simple observation, use LED_BUILTIN pin. Its a build in-LED indicator on Arduino.

pinMode(LED_BUILTIN, OUTPUT);

then

digitalWrite(LED_BUILTIN, HIGH);
delay(500)
digitalWrite(LED_BUILTIN, LOW);
delay(500)

Arduino fail on external power supply is usually because of voltage drop or your system draw too much current.


Storing array in PROGMEM I have an array of a lot of numbers (1 and 0) but i can't store them since arduino does not have enough space. How can i save an array of example 00110 in PROGMEM, then read from PROGMEM and set x to be equal lets say, third int in the array?

Store them with const byte PROGMEM with bit 0 as MSb and bit 7 as LSb per byte. E.g. 011100100101001010101011 would become const byte[] var PROGMEM {0x72, 0x52, 0xab}

Use the following macro to retrieve them (untested):

#define loadbit(mem, pos) ((pgm_read_byte(&(mem[pos / 8])) >> (7 - (pos % 8))) & 0x01)

So if you had const byte[] data PROGMEM {0x72, 0x52, 0xab}; you would call loadbit(data, 3) and it would return bit 3 starting with 0 on the left, i.e. 1.

Naturally if you needed more than one bit at a time there are probably situation-specific routines that could be used, but without knowing anything about the actual program the above will work.


NRF24 Mixing with/without antenna Is it possible to have the NRF24 module on an Arduino Mini transmitting to an NRF24 with SMA antenna on a Mega?  In that case, would the antenna on the Mega help pickup the signal of the transmitting Arduino Mini?

Yes, and yes.

A module without an antenna is exactly the same as a module with an antenna, it's just that the antenna is part of the PCB. Yes, the module with the antenna will have more sensitivity (able to receive fainter signals) as well as more transmitting power.

The same is true of the modules with the power amplifier.  They again have even more sensitivity and transmitting power.

It is quite common to have a single powerful transceiver with power amplifier and antenna as a base station and then smaller modules as the remote slave devices.  Especially if you couple the base station with a suitable parabolic or uni-directional high gain antenna to point directly at where the slave devices are.


Reset and Remove Arduino ATmega328P? So I have 2 Arduinos, and im wanting to remove the chip from one and reset it to like it came from the factory and then breadboard it and attempt to program it using an AVR programmer (Or maybe an Arduino AS a programmer).

Why? Mainly because I want to make sure I can and understand how to program the chips when I order them standalone and on a breadboard.

Is this possible? I imagine the Arduino bootloader will be on the chip and the fuses will be different, but can I over-write them if I decide to just program it as a standalone AVR chip?

Thanks!

Im just trying to learn AVR programming without the I guess "handholding" of arduino functions/etc.

You don't actually need to do anything. You don't need any breadboard, any programmer, nothing.

You can use the Arduino environment, upload facility, and board to learn low-level AVR programming.

Just because the Arduino helper functions exist it doesn't mean you actually have to use them.

The first step on your progression to professional embedded developer is to get to grips with low-level registers. You can do all that from within the Arduino environment. You have access to everything in the Arduino IDE that you have in any other IDE in the way of low-level chip functions. They are functions of the chip, not the IDE.

If you want to progress to a professional IDE and use hardware debugging you can still use an Arduino board. After all, it's just an MCU on a PCB. Just plug your hardware programmer into the hardware programming connector on the board. Why mess around with breadboards and all the trouble that they give with dodgy connections? Just because an Arduino has an Arduino logo on it you aren't forced to use it with the Arduino IDE.


What is the use of ISP and ICSP in Arduino? I am trying to connect gsm module with my arduino uno. confused about the use of isp and icsp

ISP/ICSP has no role when utilizing a typical, properly functioning Arduino, as the program code compiled from sketches is instead downloaded via a bootloader (either serial, often behind an on-board USB-serial converter, or else directly USB).

The role of ISP in the Arduino ecosystem is mostly limited to:

Loading a bootloader into new chips which do not have one, or have somehow lost theirs (note however that you can buy pre-loaded ATmega328's from many sources at a small premium)
As an alternative program loading scheme when the tiny amount of program memory used by the bootloader must be re-claimed for a particularly large sketch
Programing alternate targets to which the Arduino libraries have been partially ported, especially resource-constrained ones where the bootloader takes up a larger fraction of the total memory, such as the the ATtiny25/45/85
Replacing or modifying the firmware of an on-board USB-serial micro such as the 16u2 on an Uno to perform a different function, such as emulate a keyboard or mouse.  However, this chip can also be programmed over its USB interface in DFU mode.
Programming other non-Arduino devices used in a project (though these often have a different ISP scheme than the ATmega series).

But a typical project using purchased board(s) will involve none of these.

SPI vs. ISP

As jfpoilpret points out, a very popular way of interfacing chips to a microcontroller is the Serial Peripheral Inteface, or SPI.  Like ISP, this is a synchronous (has a distinct clock line) serial interface with a master and a slave, a mode or enable pin, and a distinct data line in each direction.  Some Arduinos use MCUs like the ATmega328p which re-use their SPI pins for ISP (with the reset functioning as the mode pin).

In effect, ISP is a sort of special "SPI-like" interface mode for programming an ATmega - often using the master-mode SPI engine of the programer to do the actual transfers.  But "ISP" applies only when programming an ATmega - the more generic case of communicating with a peripheral would be "SPI".

It's my impression that most GSM modules use asynchronous serial interfaces (ie, utilizing a UART engine), but there may be some which use SPI or other synchronous schemes, at least as an option.


Stuck in While loop when case is activated. Arduino I have an arduino uno that controls a light using an ir remote. The sketch works fine until I pressed button c which is case 0x10EF58A7. This case reads in values and dims the light accordingly but the only problem is i can not exit the case when another button on the ir remote is pressed! what should i do!?

#include <SoftwareSerial.h>

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

#include <TimerOne.h>

int RECV_PIN = 13;

IRrecv irrecv(RECV_PIN);
decode_results results;
volatile int i=0;               // Variable to use as a counter
volatile boolean zero_cross=0;  // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin = 7;
int dim2 = 0;                   // led control
int dim = 128;                  // Dimming level (0-128)  0 = on, 128 = 0ff
int pas = 8;                   // step for count;

int freqStep = 65;
char incomingByte;

void setup() {
  Serial.begin(9600);
  // initialize the digital pin as an output.
  pinMode(RECV_PIN, INPUT);
  pinMode(AC_pin, OUTPUT);
  irrecv.enableIRIn(); // Start the receiver
  attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
  pinMode(AC_pin, OUTPUT);
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);
  // Use the TimerOne Library to attach an interrupt
}

void zero_cross_detect() {
  zero_cross = true;               // set the boolean to true to tell our dimming function that a zero cross has occured
  i=0;
  digitalWrite(AC_pin, LOW);
}

// Turn on the TRIAC at the appropriate time
void dim_check() {
  if(zero_cross == true) {
    if(i>=dim) {
      digitalWrite(AC_pin, HIGH);  // turn on light
      i=0;  // reset time step counter
      zero_cross=false;    // reset zero cross detection
    }
    else {
      i++;  // increment time step counter
    }
  }
}

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

  switch(results.value){

  case 0x10EFD827:
  //power button
   dim = 00;
    Serial.println(" full brightness ");
    break;
  case 0x10EF20DF:
  //circle button
  dim = 128;
    Serial.println("off   ");
    break;
  case 0x10EFF807:
  // button A
  dim = 95;
    Serial.println(" dim level 1   ");
    break;

   case 0x10EF7887:
   //button B
   dim = 50;
    Serial.println("dim level 2     ");
    break;

 case 0x10EF58A7:
 // button C
 {
  while ( Serial.available() > 0) {
 unsigned int num = Serial.parseInt();
 num = map(num, 0, 255, 0, 128);
 unsigned int num1 = map(num, 0, 128, 128, 0);
// num1 = constrain( num1, 0,128);
 dim = num1 ;
   Serial.print(" auto   ");
   Serial.println(dim);

   delay(800);
   Serial.flush();
    //break;
   }
  break;
}
 break;

  case 0x10EF10EF:
//button left
    {
    if (dim<127)
   {
    dim = dim + pas;
    if (dim>127)
    {
     dim=128;
    }
    }
    }
    Serial.print(" dimming ammount=   " );
    Serial.println(dim);
    break;

  case 0x10EF807F:

  //button right
   {
      {
  if (dim>5)
  {
     dim = dim - pas;
  if (dim<0)
    {
      dim=0;  // in vechiul sketch era 1
    }
   }
   }
   }
     Serial.print(" dimming ammount=   ");
      Serial.println(dim);
    break;

   default:
    //Serial.print(" unknown button   ");
    //Serial.println(results.value, HEX);
{}
  }

}

void loop(){
  int i=0;
   if (irrecv.decode(&results)) {

   translateIR();
        irrecv.resume(); // Receive the next value

   }
     delay(700);
 }

The problem is that calling Serial.parseInt() does not remove data from the buffer. So, Serial.available() will not decrease in your case, but increase with every input you give.
You will need to call Serial.read() and then convert the received bytes to a number.

@Majenko generally you're right, but it's okay to use a while loop in this situation. If there is data in the buffer, this data has to be handled. And as the arduino is not capable of multitasking it will need to take the required time, no matter if in the main loop or in a subfunction.


just a silly doubt about glowing an LED what will happen if i insert the anode of a LED to pin 12 and cathode of the LED to pin 11 and set pin 12 to high and pin 11 to low,will the led glow??

What will happen is you will damage your LED and/or your Arduino since you haven't mentioned a current-limiting resistor (220 ohms could well be suitable).

However the general concept is perfectly sound. You could, for example, have two LEDs, wired in opposite directions. By bringing one pin LOW and the other HIGH, one LED would light up, and by reversing the output to the pins the other LED would light up. If both pins were either HIGH or LOW then neither LED would light up, as there would be no voltage difference between the leads.

There is a calculator for LED resistors.


Porting ATMega8 AVR based program to Intel Curie Processor I'm currently trying to port a program called 'ArduinoUSBLinker' to work on my Arduino 101 (which has an Intel Curie CPU instead of the standard ATMega CPU).

The program is used to flash ESCs without the need of additional hardware.
Arduino USB Linker

Unfortunately the code is mainly based on the ATMega's built in AVR timers,
which uses several different predefined variables such as TCCR0,TCCR1,TCTN2…

These are not available (or are they?) in the Curie Module. Since the Arduino 101 has timer functionality, I was wondering if there is a way to translate those into the Curie Timer library.

Those variables are the addresses of physical registers on the AVR that manipulate its timer/counters. Most other processors will have equivalent, but not likely identical, hardware. You'll need to port functionality, not the code.

You'll need to reverse-engineer (worst-case) the code you're trying to port (assuming you aren't intimately familiar with it, e.g., you designed it), develop a spec for it (at least in your head), and write to that spec for the Curie.

If the overall job is not (too heavily) processor-specific, you may be able to write it to be portable by writing the job-specific code in, e.g., in C, and call well-defined functions (in C or assembler) for the CPU-specific ones, that could easily be replicated on another processor.


Issues graduating to AVR-C I'm trying to make the transition from coding in the Arduino language to AVR-C, but I'm having some issues with my microcontrollers.

I don't have an ISP, so I'm using one of my Arduino UNOs with the ArduinoISP sketch. The problem is that when I try to run avrdude it gives me this error:

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
  Double check connections and try again, or use -F to override
  this check.

However, when I try to run the command with the sugested -F it uploads the code to the Arduino UNO I'm using as an ISP instead of the ATmega328p on my breadboard.

Does anyone have any idea about whats going on here, or how to fix it?

"invalid device signature" is due to bad connection or inability to reset the device (RST pin fuse setting for example).


Always 255-response in I2C between ATTiny85 (8MHz) and Arduino Uno I tried to set up an I2C conversation between ab ATTiny85 (8MHz) and an Arduino Uno. However I always get a 255 response from my I2C slave. I am using Arduino 1.8.5.

What am I doing wrong?

ATTiny85-Slave Code:

#include "TinyWireS.h"  // wrapper class for I2C slave
routines
#define I2C_SLAVE_ADDR  0x26 // i2c slave address (38)

byte t=10;

void setup() {
  TinyWireS.begin(I2C_SLAVE_ADDR);  // init I2C Slave mode
  TinyWireS.onRequest(requestEvent);
}

void loop() {
}

void requestEvent() {
  TinyWireS.send(t);
}

Arduino Uno-Master Code:

 #include <Wire.h>
 #define I2C_SLAVE_ADDR  0x26 // i2c slave address (38)

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

void loop() {
  byte num;
  // read 1 byte, from address 0x26
  Wire.requestFrom(I2C_SLAVE_ADDR, 1);
  while(Wire.available()) {
    num = Wire.read();
  }
  Serial.print("num = ");
  Serial.println(num,DEC);
}

It may seem that the current commit of January 2018 from the TinyWire library is corrupt. Try using an older version from 2017, for example this one: https://github.com/rambo/TinyWire/tr...72a13504bbfc4e

This solves the problem for me as well.

Source: Teensy 3.5 - I2C - ATTiny85-20PU (TinyWireS.OnRequest not triggering!) - Post #11


Attiny85, high output impedance, dim leds I designed what I thought should be a very simple badge using the Attiny85 SU, schematic below:

The problem is the tiny doesn't seem to be sinking current properly. For testing I switched to a 20 PU on the breadboard and 100 ohm load resistors. At 3v supply this should give approximately 30 mA per pin, well under the rated 40 mA per pin and 200 mA total. However with the loads connected only pin 6 sinks any significant current, and appears to be higher impedance than it should be (1.6v across the resistor for 16 mA). The other pins seem to be very high impedance, they drop to ~7 mV (70 microamps) when the loads are connected. With the load resistors disconnected they function normally (digitalWrite HIGH = supply voltage - junction drop).

I'm using pinMode [this was a problem] (OUTPUT, N) [/this was a problem, should be (N, OUTPUT)] to set up pin N, and digital writes for on/off. I've been able to drive transistors before using an exactly similar setup, although admittedly these have much lower current requirements.

Anybody know what's going on here?

EDIT: Turns out I had accidentally swapped the order of OUTPUT and N in the pin mode command. Not sure why the compiler had no problems with this, but I am at least getting useful outputs now.

I'm gonna leave this up out of curiosity/etc, because I'm still getting higher impedance than I'd have expected on the outputs. With the 100 ohm load resistor, I'm only getting about 16 mA (expect closer to 25). Supply voltage from the CR2032 is ~2.48v under load.

Based on the graph on the datasheet (figure 22-19, PG 182), at 25 c ambient (currently 20) I should expect a voltage drop from VCC to output somewhere on the lower end between 400 and 600 mV when supplying 15 mA, but my readings at 16 mA above represent a voltage drop of almost 900 mV across the Tiny. Additionally the LEDs drop 2v at 10 mA, for which you'd expect approximately 300 mV drop across the tiny according to the graph, but mine is dropping almost 500 mV. I'm not sure if this is something in my setup or if the characteristic curves on the datasheet simply aren't that accurate for production models.

You already found your problem. I am answering only to provide some
insight on why you were experiencing the symptoms you had.

pinMode() takes two integer arguments (two uint8_t to be precise).
The names INPUT, OUTPUT and INPUT_PULLUP are just macros for 0, 1
and 2 respectively. This is why the compiler accepts your code with the
arguments swapped.

On the AVR microcontrollers, setting a pin's output register to HIGH
on a pin that is configured as input has the effect of turning on the
internal pullup. Thus

digitalWrite(pin, HIGH);

has the same effect as

pinMode(pin, INPUT_PULLUP);

on an input pin. When you do this, the pin will source (not sink) a very
small current. The pullup resistance is typically of the order of
30 kΩ, and this is why you get such a small current.


Get Battery voltage on raw I power my Arduino Mini with 3 AA batteries on RAW input. Is it possible to get the voltage on RAW and therefore the expected longevity of the batteries?

No. Not directly. You can use voltage divider and measure the result with using internal reference. But it's another current consumption and you can't reduce it by (for example) entering one of the sleep modes.

And if you have 5V Arduino Mini variant, you can power it directly through 5V power pin. Otherwise you are losing about 1.5V on voltage regulator. On 3.3V variant it might be better, but it also depends on used regulator voltage drop and would be better to power it directly (if you don't have connected anything strictly with 3.3V power, and for AVR based Arduinos it's not a problem)

Anyway, if you power it directly, you can measure the power source voltage by measuring internal bandgap voltage reference against power as reference. But, as far as I know, it can't be done by analogRead, as it doesn't support other sources than analog pins.


4 digit 7-segment display What happends if I turn on all LEDs at the same time in an 4 digit 7 segment display? that would be 32 LEDs turned on at once, wouldn't that exceed the 200ma MAX for the arduino output?

The key point is that if you do that, you're doing it wrong.

Typically a multi digit display is time multiplexed, such that you use a common set of segment lines to activate the pattern on each digit in turn, therefore at any one time only at most 7 (or 8 counting the decimal point) segments should actually be on.

Then in terms of the common connection which selects a given digit, this will indeed typically have to source or sink more current than an MCU I/O pin is typically rated to handle, so it's best if the common connection is driven by an external transistor or FET.

Other options of course include mutli-digit LED display drivers, or lower power display technologies like LCDs.

That said, if a software bug briefly means everything is on, chances are the chip will survive.  But hopefully this only happens to "engineering units" - you do want to make sure that production units don't suffer this at some point in the programming process or something like that (though that's not all that likely, as typically all I/Os become inputs with at most a weak pullup).


Supervised inputs for alarm panel I'm using an Arduino Mega 2560 to make a fire alarm control panel. The control panel takes 50 (inputs) supervised inputs. The normal way as mentioned in the link is to use the analog inputs, which I am short of. Is there any other way to monitor supervised inputs other than using analog inputs?

Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.

I can think of a number of ways of doing this:

Multiplexing -- Employ a (large) number of analog MUX chips to expand the number of analog inputs you have available. That would get messy very quickly.
External ADC Chips -- Add more real analog inputs over SPI or I2C. For 50 inputs that would be quite a lot of extra chips.
Use Op-Amps -- Each input can be converted into a pair of digital inputs using two op-amps to compare the voltage of the input against two thresholds, which would give you an "active" and a "fault" signal. That would be 100 digital inputs needed (and 100 op-amps, which could be done with 25 quad op-amp chips).
Distributed processing -- Don't try and do it all with one device. Split your system into zones with far less inputs then get the zones to communicate with each other.

Of course, you can combine any of those - you could have analog MUX chips fanning out a number of external ADC chips inputs. You could MUX the inputs to the op-amps. You could have external ADC chips on multiple zone systems. Etc.

Personally, on a system of this size, I would certainly consider distributing the inputs across multiple processors even if they are all in the same physical control unit. However, distributing nodes across the building (it sounds like it's quite a large building for 50 inputs) would reduce the amount of cable needed to implement those inputs, and some industry standard bus snaking its way around the building connecting all the nodes up to a master unit would, if implemented correctly, be robust. CAN is a popular protocol for interconnecting control systems (it's used in modern lifts, and those are life critical... you don't want a lift to fail...) so could be a good choice for this.


Arduino master/slave communication using RS485 I am using Arduino Uno as a Master Device and 3 Arduino Unos as slave devices.

I am sending data from each slave to master after every 3 seconds continuously, and is going to execute further logic accordingly.

I have been using a lot of libraries to test this scenario.
There are libraries which are using SoftwareSerial and HardwareSerial too, but these libraries are not working for me when i have multiple slaves and one master (It is only working with one master and one slave).

Please suggest me a better library which would be useful in my scenario.

Wiring Diagram:

First of all, your connection is just wrong, you should make the RS-485 bus as a straight line, with a 120 ohm resistor at the beginning and another one at the end. Each slave should tap into that line as close as possible to that line, look for datasheets and you will understand what I am talking about.

Second, you can use Modbus as a pretty good and easy to use communication protocol.


reversing DC motor rotation using TWO limit Switches Problem !! need help I'd like to write a code for reversing DC motor rotation direction as follows:

Start the motor rotation clockwise (CW).
When reach Limit Switch (CW) → motor will stop for 5 sec.
after 5 sec. of stopping → the motor will rotate in counter clockwise direction(CCW).
When reach Limit Switch (CCW) → motor will stop for 5 sec.

and repeat point 1, 2, 3 and 4...

Actually I wrote a code for reversing the motor direction using two limit switches and it is working good. But when I added delay the motor did not stop using the limit Switches and continue to rotate...
If any one can help...
Here is my code for reversing the direction with out delay 5 sec. My limit SWs are connected on Normal Open.

int sw1, sw2, sw3;
const int LM1 = 0;
const int LM2 = 1;
const int LM3 = 6;
const int CW = 10;
const int CCW = 9;
const int Buzzer = 7;

void setup() {
  pinMode(LM1, INPUT);
  pinMode(LM2, INPUT);
  pinMode(LM3, INPUT);
  pinMode(CW, OUTPUT);
  pinMode(CCW, OUTPUT);
}

void loop(){
  sw3 = digitalRead(LM3);
  sw1 = digitalRead(LM1);
  sw2 = digitalRead(LM2);

  if (sw1 == LOW && sw2 == HIGH) {
    do {
      digitalWrite(Buzzer, HIGH);
      digitalWrite(CW, HIGH);// change the direction of rotation (DOWN Movement)
      digitalWrite(CCW, LOW);

      sw2 = digitalRead(LM2);
    } while (sw2 == HIGH);
  }
  else if (sw1 == HIGH && sw2 == LOW) {
    do {
      digitalWrite(Buzzer, HIGH);
      digitalWrite(CW, LOW);// change the direction of rotation (UP Movement)
      digitalWrite(CCW, HIGH);

      sw1= digitalRead(LM1);
    } while (sw1 == HIGH);
  }
}

Normally you use state machine for this kind of programming: you have a
state variable that remembers what you are doing, and depending on the
current state you decide what to do next. Below is an example with two
states. I have embedded a few assumptions about the wiring of your motor
and your switches, which may be wrong, so you have to check the code.

void loop() {
    static enum {MOVING_CW, MOVING_CCW} state;

    switch (state) {
    case MOVING_CW:
        if (digitalRead(LM2) == LOW) {  // hit switch
            digitalWrite(CW, LOW);      // stop
            delay(5000);
            digitalWrite(CCW, HIGH);    // restart
            state = MOVING_CCW;
        }
        break;
    case MOVING_CCW:
        if (digitalRead(LM1) == LOW) {  // hit switch
            digitalWrite(CCW, LOW);     // stop
            delay(5000);
            digitalWrite(CW, HIGH);     // restart
            state = MOVING_CW;
        }
        break;
    }
}

This will start in the MOVING_CW state, but you have to actually start
the movement in setup(). It has the drawback of having long delay()s in
the loop, which is undesirable if you have other tasks to perform. These
delays can be removed by “remembering” that you are waiting as two extra
states:

void loop() {
    static enum {MOVING_CW, MOVING_CCW, STOPPED_CW, STOPPED_CCW} state;
    static unsigned long time_stopped;
    unsigned long now = millis();

    switch (state) {
    case MOVING_CW:
        if (digitalRead(LM2) == LOW) {  // hit switch
            digitalWrite(CW, LOW);      // stop
            state = STOPPED_CW;
            time_stopped = now;
        }
        break;
    case MOVING_CCW:
        if (digitalRead(LM1) == LOW) {  // hit switch
            digitalWrite(CCW, LOW);     // stop
            state = STOPPED_CCW;
            time_stopped = now;
        }
        break;
    case STOPPED_CW:
        if (now - time_stopped >= 5000) {
            digitalWrite(CCW, HIGH);    // restart
            state = MOVING_CCW;
        }
        break;
    case STOPPED_CCW:
        if (now - time_stopped >= 5000) {
            digitalWrite(CW, HIGH);     // restart
            state = MOVING_CW;
        }
        break;
    }
}


Source Code for strcpy and strcat Does anyone know the location of the assembler file for strcpy and strcat for the Arduino?  I wish to modify it.

The Arduino IDE doesn't ship with the source/assembly for a lot of the core functionality. It comes pre-compiled in object/library files.

However, you could download the source code for AVR Libc from this site:

http://www.nongnu.org/avr-libc

Obviously there's no guarantee that the files you download will exactly match what comes with the Arduino IDE, but it's useful if you're interested in how they're implemented.

When you've downloaded and extracted the source code, look in the libc/string folder. you should find assembly files called strcat.S and strcpy.S.

As jfpoilpret says in the comments, attempting to modify core library functions is generally not a good idea. They may be getting called by other parts of the core, so any changes you make could break something else.


Porting Arduino code to AVR/C++ input not working? So. I'm trying to read an input on the Arduino Nano using C++/AVR/Eclipse instead of the regular arduino IDE.
The code below is working in the arduino IDE

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
  pinMode(5, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(digitalRead(5)){
    digitalWrite(13,1);
  }else{
    digitalWrite(13,0);
  }
}

I'm porting the code to AVR/C++ in Eclipse, regular blinking leds is working... but I can't read inputs for some reason...

#define F_CPU 16000000UL //16MHz
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;//Setting all portB pins to output (D13/PB5 - LED)
    DDRD = 0x00;//Setting all portD pins to input  (D5 /PD5 - INPUT)

    while(1){
        if(isset_bit(PORTD,PD5)){//if input... doesn't work?
            set_bit(PORTB,PB5);//Set output (Tested to be working)
        }else{
            clear_bit(PORTB,PB5);//Clear output
        }
    }
}

During the creation of this question I found out the answer... Though I wanted to share it with you guys for later reference.
It has been quite a time since I have worked with AVR.

You should read pins from PINx

You should set pins in PORTx

Set DDRx to 1 for OUTPUT and to 0 for INPUT

^ This is fun because PIC/Microchip MCU's use 1 for input and 0 for output.

See code below:

#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>

#define set_bit(Y,bit_x) (Y|=(1<<bit_x))
#define clear_bit(Y,bit_x) (Y&=~(1<<bit_x))
#define isset_bit(Y,bit_x) (Y&(1<<bit_x))
#define toggle_bit(Y,bit_x) (Y^=(1<<bit_x))

int main( ){
    DDRB = 0xFF;
    DDRD = 0x00;

    while(1){
        if((PIND&(1<<PD5))){
            set_bit(PORTB,PB5);
        }else{
            clear_bit(PORTB,PB5);
        }
    }
}


How are PCB's programmed? So recently I have been looking into prototyping my arduino project and there are a lot of tutorials online on how to take your Arduino and using a software such as Eagle to make a PCB layout but I was wondering how you would get the Arduino program onto that PCB. Surely in large scale circuit manufacturing they wouldn't have a usb attached so that they upload a program into each and every one of their circuits?

why not?

Well ok ... they might not connect a USB to each one as there are faster ways - flyingProbe/PogoPins on a "bed of nails"

http://en.wikipedia.org/wiki/In-circuit_test

This type of temporary connection speeds up testing & pre-programming considerably.

Each card that is made has to go through some form of test process at the end (flying probe or manual).

https://learn.sparkfun.com/tutorials/electronics-assembly

  On boards that require programming or calibration, additional steps
  are taken to load code and verify the output.