Arduino potentiometer (external power) with amplifier i am trying to make some kind of an amplifier. I got an amp board but want to read out the value from the potentiometer. The problem is that this pot is connected to the amp and has to be connected to the amps power Is there any way i can still read data (with an arduino) so that i can have a volume percentage on a lcd? Or is this imposible?

Amp 24v Potentiometer = 6pin. B50k

also what zould happen if i connect a 10k resistor instead of a 50k ressistor (audio potentiometer) what would the effect be?

It's impossible. The pot is most probably acting as a passive variable attenuator. As such the top end will be the incoming audio signal, the lower end will be ground, and the wiper will be the attenuated incoming signal. There's not a lot you can do with that.

You would need to replace the pot with an equivalent triple pot (if such a thing exists) and have one third of it connected to the Arduino.  The pot you have at the moment is a dual pot, and a log taper at that.

Alternatively adding some kind of quadrature (motor) encoder to the shaft of the pot may be a possibility.


Arduino "piston" device Is there any compact piston-like devices on the market that can apply pressure safely various parts of the head? I can further expound if needed.

The ideal size would be something within the 1-2 inch length range

It sounds like this is nothing to do with an Arduino, just a general Electrical/Mechanical engineering question that you want to control from and Arduino.
I think you wan a device that when signalled by your Arduino can extend itself by up to 2 inches.

If that is right then I think what you are looking for is a Linear Actuator.  There are plenty out there and some do handle the small stroke you want, but most of them appear to be 9 to 12V.  This means you would require a Darlington transistor or relay to control them from an Arduino.

If you require an extremely precise stoke length then I would recommend a stepper motor with a screw axel.  This would allow you much finer control over how far you pushed, but it would impose limits on what you could do and how it could be mounted.

Can you provide more details on what you want to move?
List item
Is it heavy? Do you need lots of Torque?
Are you pushing straight or do you need to push in an arc (i.e. a door)?
What voltage supplies do you have available?
How fast do you want it to move?
Do you want it to move exactly the same distance every time?

The more info you can provide the better, but in answer to your original question Yes, it sounds like there might be so you plan is still on the rails.


Adding fade to this RGB LED IMU I've built an accelerometer based dice. It changes colour based on what side of the dice faces up. All is well and good, except I'd like the RGB to fade from one colour to the next instead of changes instantly.

Here's the code:

include <Wire.h>
include <Adafruit_Sensor.h>
include <Adafruit_LSM303_U.h>
include <Adafruit_9DOF.h>
include <Adafruit_L3GD20_U.h>

/* Assign a unique ID to the sensors */
Adafruit_9DOF                 dof   = Adafruit_9DOF();
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(30301);
Adafruit_LSM303_Mag_Unified   mag   = Adafruit_LSM303_Mag_Unified(30302);

// OUTPUT: Use digital pins 9-11, the Pulse-width Modulation (PWM) pins
// LED's cathodes should be connected to digital GND
int redLEDPin = 11;   // Red LED,   connected to digital pin 9
int greenLEDPin = 10;  // Green LED, connected to digital pin 10
int blueLEDPin = 9;  // Blue LED,  connected to digital pin 11

// Program variables
int red = 255;   // Variables to store the values to send to the pins
int green = 255;
int blue = 255;

int lastOrientation = -1; // previous orientation

void initSensors()
{
  if(!accel.begin())
  {
    Serial.println(F("No LSM303 detected"));
    while(1);
  }
  if(!mag.begin())
  {
    Serial.println("No LSM303 detected");
    while(1);
  }
}

void setup() {

  Serial.begin(115200);
  Serial.println(F("RGB Dice... go!")); Serial.println("");

  /* Initialise the sensors */
  initSensors();

  pinMode(redLEDPin, OUTPUT);   // sets the pins as output
  pinMode(greenLEDPin, OUTPUT);
  pinMode(blueLEDPin, OUTPUT);

  int lastOrientation = -1; // previous orientation
}

void loop() {

  /* Get a new sensor event */
  sensors_event_t event;
  accel.getEvent(&event);

  int orientation = - 1; // dice orientation
  String orientationString; // string for printing orientation
  /*
   * orientation:
   * 1: cyan
   * 2: blue
   * 3: green
   * 4: magenta
   * 5: yellow
   * 6: red
   */

  // read accelerometer
  int x = event.acceleration.x;
  int y = event.acceleration.y;
  int z = event.acceleration.z;

  // calculate absolute values, and determin largest
  int absX = abs(x);
  int absY = abs(y);
  int absZ = abs(z);

  if ( (absZ > absX) && (absZ > absY)) {

    //base orientation Z
    if (z > 0) {
      orientationString = "1, cyan";
      orientation = 1;
      red = 255;
      green = 0;
      blue = 0;

    } else {
      orientationString = "6, red";
      orientation = 6;
      red = 0;
      green = 255;
      blue = 255;
    }

  } else if ( (absY > absX) && (absY > absZ)) {

    //base orientation Y
    if (y > 0) {
      orientationString = "2, blue";
      orientation = 2;
      red = 255;
      green = 255;
      blue = 0;

    } else {
      orientationString = "5, yellow";
      orientation = 5;
      red = 0;
      green = 0;
      blue = 255;
    }
  } else {
    //base orientation X
    if (x > 0) {
      orientationString = "4, magenta";
      orientation = 4;
      red = 0;
      green = 255;
      blue = 0;

    } else {
      orientationString = "3, green";
      orientation = 3;
      red = 255;
      green = 0;
      blue = 255;

    }
  }

  // if orientation changes, print out a description
  if (orientation != lastOrientation) {
    Serial.println(orientationString);
    lastOrientation = orientation;
  }

  analogWrite(redLEDPin, red);   // Write values to LED pins
  analogWrite(greenLEDPin, green);
  analogWrite(blueLEDPin, blue);
  delay(100);

}

Every fading example I have adopted has broken the code so far. I guess my initial code isn't set up for it. Any ideas for a workaround?

You need to be a little clearer about the time that can exist between the sensor values changing. If you fade to slowly the correct value might never be reached before the sensor changes again. Maybe that's what you want?

You can't use a delay().

You need a currentRed, currentGreen and currentBlue so you can fade to the values of red, green and blue.

unsigned long last_reading_ms;
int red = 255;   // Variables to store the TARGET rgb target values for each pin
int green = 255;
int blue = 255;
int currentRed = 0;   // Variables to store the current rgb values of the pins
int currentGreen = 0;
int currentBlue = 0;

void setup()
{
   last_reading_ms=millis();
}

void loop()
{
  /* read sensor every 100ms and set red, green,blue if changed */
  if (millis()-last_reading_ms > 100)
  {
    /* Get a new sensor event */
    sensors_event_t event;
    accel.getEvent(&event);
    //the rest of your sensor reading code here

    last_reading_ms=millis()
  }

  /* if orientation changes, print out a description */
  if (orientation != lastOrientation) {
   Serial.println(orientationString);
   lastOrientation = orientation;
  }

  calculateRGBFadeTo();

  analogWrite(redLEDPin, currentRed);   // Write values to LED pins
  analogWrite(greenLEDPin, currentGreen);
  analogWrite(blueLEDPin, currentBlue);

  //*** do not use a delay or use a very small one to slow the transition ***
  //delay(100);

}

/* get values 1 step closer to target red, green, blue */
void calculateRGBFadeTo()
{
  /* fade to required rgb values */
  if (currentRed<red)
   currentRed ++;
  else if (currentRed>red)
   currentRed --;

  if (currentGreen<green)
    currentGreen ++;
  else if (currentGreen>green)
    currentGreen --;

  if (currentBlue<blue)
    currentBlue ++;
  else if (currentBlue>blue)
    currentBlue --;

}

Notes:

The fade can be slowed down either with a small delay such as 5 ms. or by using another millis() variable to determine the time since the led was last set.

For example: if (millis()-last_rgb_write_ms > 5)

It's also possible to speed up the fade by using a larger increment. An increment of two, for example, currentRed+=2; instead of currentRed++;

Reminder, the comparison of when the target red, green, blue has been reached will be more complex with an increment greater than 1.

An increment of 2 and a sensor read frequency of 128ms (instead of 100) would ensure the correct RGB values are always reached. Alternatively reading the sensor every 255ms (4-5 times per second) would also ensure the correct RGB values has been reached.

Using millis() and avoiding delays allows many more tasks to be performed with more accurate timings.


How are locations in FLASH memory addressed? There is an external FLASH memory (W25Q80DV) that I want to use with the Arduino.
This memory has 4096 pages of 256 bytes each.
I want to make multiple writes per page to use memory evenly and erase less.
Test code:
#include <SPI.h>

#define readStatusReg_1 0x05
#define readArrayReg 0x0B
#define writeEnableReg 0x06
#define pageProgramStatusReg 0x02

#define FLASH_SELECT_CHIP 33

// # Select / Unselect chip
void selectChip(bool state) {
  switch (state) {
    case true:
     digitalWrite(FLASH_SELECT_CHIP, HIGH);
     digitalWrite(FLASH_SELECT_CHIP, LOW);
      break;
    case false:
     digitalWrite(FLASH_SELECT_CHIP, HIGH);
      break;
  }
}

// # Wait flash ready state
void notBusy() {
  uint16_t whileCounter;
  selectChip(true);
  SPI.transfer(readStatusReg_1);
  while((SPI.transfer(0) & 1) && whileCounter < 45000) { whileCounter++; }
  selectChip(false);
}

// # Send command and address
void sendCommandAndAddress(const byte command, const unsigned long address) {
  SPI.transfer(command);
  SPI.transfer((address >> 16) & 0xFF);
  SPI.transfer((address >> 8) & 0xFF);
  SPI.transfer(address & 0xFF);
}

// # Write enable
void writeEnable() {
  notBusy();
  selectChip(true);
  SPI.transfer(writeEnableReg);
  selectChip(false);
}

// # Write FLASH page
bool writeFlashData(const unsigned long address, byte * data) {
  writeEnable();
  selectChip(true);
  sendCommandAndAddress(pageProgramStatusReg, address);
  uint16_t len = sizeof(data);
  for(uint16_t i = 0; i < len; i++) {
    SPI.transfer(*data++);
  }
  selectChip(false);
  notBusy();
  return true;
}

void setup() {
  // SPI
  pinMode(FLASH_SELECT_CHIP, OUTPUT);
  digitalWrite(FLASH_SELECT_CHIP, HIGH);
  SPI.begin();
  SPI.setDataMode(0);
  SPI.setBitOrder(MSBFIRST);

  // Write FLASH
  #define TESTADDRESS 0x1000
  byte msgData[] = "Hi all!";
  writeFlashData(TESTADDRESS, msgData);
}

void loop() {}

Here, the address #define TESTADDRESS 0x1000 (4096) is specified for writing data.
I'm not clear if this is the page address or the byte address from which I will start recording?
I would like to actually split one page into multiple blocks and write data for them separately.

I'm not clear if this is the page address or the byte address from which I will start recording?

That is the byte address.  As the data sheet in section 8.5.13 says:

If an entire 256 byte page is to be programmed, the last address byte (the 8 least significant address bits) should be set to 0. If the last address byte is not zero, and the number of clocks exceed the remaining page length, the addressing will wrap to the beginning of the page.

In other words: if you want to write an entire page then start at the beginning of the page. If you don't and you write more than there is room left in the page you will wrap round back to the beginning of the page again.
So if you write two bytes starting with address 0x10FF you will actually write one at 0x10FF and the second at 0x1000, not 0x1100, since you wrap at the page boundary.


Internal volts in arduino for percent battery I'm working on a small project that is creating me a headache. I know arduimo (ATmega 328P .... etc. ..) has an internal voltage source code millivolts, but I would like to know how the full source code become percentage where 3 volts = 0%  and 4.2 volts = % 100% ??? . I appreciate the help because in codes is not my forte. I leave the code so Help me complete. Thank you.

long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

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

void loop() {
  Serial.println( readVcc(), DEC );
  delay(1000);
}

map()

unsigned char level = map(readVcc(), 3000, 4200, 0, 100);


Adafruit thermal printer prints weak I am currently hooking up my arduino to an adafruit mini thermal printer. When a button is pressed, some code is executed which then sends some information to the thermal printer.

Everything works fine except the thermal printer print is very weak and can barely be seen as soon as the printer needs to print more than 3-5 chars. Any ideas why? Both, the arduino and the thermal printer are hooked up to 9V batteries.

Here is the code

#include "Adafruit_Thermal.h"

// Here's the new syntax when using SoftwareSerial (e.g. Arduino Uno) ----
// If using hardware serial instead, comment out or remove these lines:

#include "SoftwareSerial.h"
#define TX_PIN 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define RX_PIN 5 // Arduino receive   GREEN WIRE   labeled TX on printer

SoftwareSerial mySerial(RX_PIN, TX_PIN); // Declare SoftwareSerial obj first
Adafruit_Thermal printer(&mySerial);     // Pass addr to printer constructor

int buttonIn = 8;
int val = 0;

void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, LOW);

  pinMode(buttonIn, INPUT);

   mySerial.begin(19200);  // Initialize SoftwareSerial
   //Serial.begin(19200); // Use this instead if using hardware serial
   printer.begin();        // Init printer (same regardless of serial type)
}

void loop() {
  // put your main code here, to run repeatedly:
     val = digitalRead(buttonIn);
     if(val == HIGH)
     {
        printer.println("test");
        printer.sleep();      // Tell printer to sleep
        delay(3000L);         // Sleep for 3 seconds
        printer.wake();       // MUST wake() before printing again, even if reset
        printer.setDefault();

     }
}

Did I set up anything false? Is the power supply not enough?
The adafruit was sent with a selftest from the seller where everything seemed to be fine.

Left, seller test, second from left, my selftest, third and fourth from left are example printer and charset tests.

And here you can see how everything is wired together.

Thank you very much!

The datasheet states:
Requires 5-9VDC @ 1.5Amp power supply during print.

In my experience this printer provides best results when operated at its upper limit. I am using a 9V 2A power supply for that. A bettery is definitiverly not enough.


Program ESP01 and keep it after reboot I am bit of a noob when it comes to ESP programming. I have an ESP01 and a USB programmer for it, but every time I unplug it, it resets, which makes me wonder how can I make it battery-powered since every reboot resets the program.

The ESP-01 ... and all ESP8622 ... have two modes for operation.

Flash mode / Boot load mode - on bootup (at the time an electrical current is first applied, or after the reset pin is grounded), if the GPIO0 (GPIO Zero) pin {On the ESP-01 this is the 7th pin} is connected to ground, the chip goes into non-run, receive program mode.  This is where you load the compiled program.

Normal - on bootup (as above), but GPIO0 is NOT ground, then the ESP-01 goes into run mode.


sbi() and cli() implementation I've often seen cli() and sbi() in Arduino code. I usually don't mind them as I know what they do (clear or set the bit given as second argument in the register of the microcontroller given as first). I've always thought that those functions where only a clear way to perform simple bit manipulation, which can be quite error-prone. Something like that:
#define cli(reg,bit) (*reg &= ~(1 << bit) and #define sbi(reg,bit) (*reg |= (1 << bit)).

Then I found out that the actual implementation is as follows:

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

It's quite like I used to think... but with two extra macros.
I looked for them in the Arduino libraries:

#define _BV(bit) (1 << (bit))

and

#define _SFR_BYTE(sfr) _MMIO_BYTE(_SFR_ADDR(sfr))

which contains

#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

and

#if _SFR_ASM_COMPAT
#if (__SFR_OFFSET == 0x20)
#define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)
#elif !defined(__ASSEMBLER__)
#define _SFR_ADDR(sfr) (_SFR_IO_REG_P(sfr) ? (_SFR_IO_ADDR(sfr) + 0x20) : _SFR_MEM_ADDR(sfr))
#endif
#else  /* !_SFR_ASM_COMPAT */
#define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)

Further research took me to definitions I couldn't understand (for example because they are explained in comments using a lot of acronyms I don't know).
So I have the following questions:

Why is sfr casted to *(volatile uint8_t *)?
What do the acronyms used in that code mean? (ASM, SFR, MMIO)
Under what circumstances is __ASSEMBLER__ defined, and where (in which file)?
Why can't we simply write #define cli(reg,bit) (*reg &= ~(1 << bit) and #define sbi(reg,bit) (*reg |= (1 << bit))?

On Atmel (now Microchip) AVR microcontrollers, the sbi, cbi, sbis, and sbic assembly language instructions can only address the 32 IO ports at addresses between 0x20 and 0x3f. The Atmega168 and 328 (used in Arduinos prior to the Leonardo) has WAY more than 32 IO registers, so only a subset of them can be addressed by sbi and cbi (the AVR instruction set was nailed down YEARS ago, when 32 IO registers seemed like more than enough).

As a result, operations that set or clear a single bit in those 32 IO registers can be performed by a single instruction which executes in two clock cycles, but the same operations on the remaining IO registers require a full-blown load-operate-store sequence that takes at least three cycles to execute.

From what I recall, AVRlibC had multiple macros that did almost the same thing, but had different use cases:

One would compile to the fastest and most efficient instruction(s) available for that particular IO address.
One would always compile to sbi/cbi, and would throw a compiler error if you tried to access a register outside of 0x20-0x3f
One would ALWAYS compile to the load-act-store sequence, without regard to whether or not it could have used sbi/cbi instead.
One would always compile to the load-act-store sequence, but would throw a compiler error if you tried using it on an address between 0x20 and 0x3f.

Basically, the choice enabled you to decide between optimized (but variable) performance, uniformly-slow (but deterministic) execution time, or the fastest-possible (but deterministic-at-compile-time) variant [which required that the programmer be aware of whether the register in question was within or above 0x20-0x3f].


How to select which resistor is required for my curcuit to reduce voltage I am trying to connect arduino and esp8266 as like this

I know arduino runs at 5V and RX of ESP8266 should not have voltage more than 3.5V. If you see my diagram there voltage is large than need on RX of ESP8266. I know resistor can help me for this and ohm law.

V = R.I => R = V/I

So I want to understand how should I select what ohm resistor for this cuicuit ? Can anyone explain with some calculation using ohm law ?

A resistor can only drop a certain voltage when there is a certain current - as you know from Ohm's Law.  If you have resistance R and current I the voltage dropped is R×I.

So if the current changes the voltage changes - and if the voltage changes the current changes.

So what do we do? Well, we have one known fixed value, and that is the 5V from the GPIO pin. And since that is fixed (at least when HIGH) we could add a fixed resistance to it to give a fixed current, right?

So let's do that. Pick a random value. Experience teaches you that certain values are better than others, but the actual value doesn't matter too much, as long as:

It's not so small that too much current flows out of the GPIO pin, thus damaging it, and
It doesn't create too high an output impedance, which we will come on to later.

10kΩ is a good figure to start with. Not only does it keep the current low enough, but it's pretty much guaranteed that you'll have one in your bits box somewhere. And we connect it to the GPIO like this (we completely ignore the ESP8266 for the moment):

simulate this circuit – Schematic created using CircuitLab

When TX is HIGH it's at 5V. It's connected directly across a 10kΩ resistor, so therefore we can use Ohm's Law to calculate the current - I=V÷R = 5 ÷ 10,000 = 0.0005, or 0.5mA. (Another useful thing with 10kΩ resistors is it makes calculations nice and easy).

Now, what if we were to split that resistor in half, so it was two 5kΩ resistors in series? The circuit would look like this:

simulate this circuit

Resistors in series add together, so those two 5kΩ resistors are the same as one 10kΩ resistor. We know that 0.5mA flows through 10kΩ at 5V, so the same must run through 5+5kΩ at 5V. But now we have two fixed value resistors. Because of that we can now apply Ohm's Law to each one to find the voltage drop across it.

So with 0.5mA flowing through a 5kΩ resistor we get V=I×R = 0.0005 × 5000 = 2.5V.  That's 2.5V across R1 and 2.5V across R2, since they are both the same. That's exactly 50% of the 5V across each one. At the point in the middle, point "A" on the schematic, you can see that the voltage has been cut in half. Once the current has gone through one resistor the voltage has halved (dropped by 2.5V), and when it goes through the other resistor it drops the rest to 0V, which is the other 2.5V.

If we were then to connect something to point A it would see a logic signal of 0V (LOW) and 2.5V (HIGH) from our 0V (LOW) and 5V (HIGH) signal.

But 2.5V is too low for the ESP8266 to read. Well, the answer is simple. We see that if we use two resistors we divide the voltage into two. The same applies for dividing it into three. For instance:

simulate this circuit

The sum is 10kΩ (well, 9.9kΩ but we'll call it 10kΩ for simplicity - a third each resistor, 3333.33Ω). 0.5mA through 3.3kΩ would be 0.0005 × 3333 = 1.66V. Funnily enough, 5 ÷ 3 = 1.66, so we have proved that it splits it into a third. That means at point A 1.66V of our 5V has been dropped (across R1), so 5V is now (5-1.66) 3.33V. Perfect for the ESP8266. Incidentally, point B would be 1.66V (3.33 - 1.66).

So now we have three resistors and the result we desire. However it's a little messy still. Remember that resistors in series add together? So why not add R2 and R3 together into a single resistor? That would be 6.6kΩ. Now I don't know of a 6.6kΩ resistor that's easily available, but 6.8kΩ ones are, though chances are you may not have one. If you did then a 3.3kΩ and a 6.8kΩ would net us near enough 3.3V to be usable.

But as I say you may not have one. So you pick resistor values that you do have. For instance you could use a 2.2kΩ and a 4.7kΩ, or a 10kΩ and a 22kΩ - anything that gives a roughly 1:2 ratio of value (the "upper" R1 resistor about half the value of the lower "R2" resistor).

Now - we get onto that mysterious phrase I mentioned earlier: Output Impedance. You recall we calculated the current that flows through the resistors - 0.5mA. The higher the value of resistors we use the lower the current. Well, that current not only flows through the resistors - a small amount also heads off into the ESP8266. The more that the ESP8266 wants for its RX pin the less there will be available for the R2 resistor. The result? Less current through the resistor = less voltage dropped across it.

The current drawn by the pin attached to point A on our circuit affects the voltage dropped across the resistors.

Too much current drawn and the voltage at point A will droop. Less will be dropped across the (current starved) R2, which means more must be dropped across R1. So point A is now a lower voltage. If that gets too low (too much current is drawn) then the RX pin can't read it properly.

Increasing the resistances decreases the current, but also decreasing the resistances increases the current. If the current is increased then the fraction of the current needed by the RX pin becomes reduced compared to what is available, so the output voltage drops less.

This output impedance, in case you're interested, is measured in Ohms, and is the same as the value of the two resistors in parallel - so (R1×R2)÷(R1+R2).

For instance, I tried connecting an ESP8266 the other day using 3 10kΩ resistors - R1 = 10K, R2 = 20K. It didn't work. You'd expect it to, given the ratios involved, however the output impedance (6.66kΩ) was too high for the ESP8266 I was using. Replacing them for 1kΩ resistors, so it was 666Ω output impedance, made it work straight away.

You can understand it easier if you think of the ESP8266 as just another resistor (it's actually more complex than that - it's also like a capacitor, so it forms a low pass filter which limits the frequency of, and deforms the shape of, the incoming digital waveform). For example:

simulate this circuit

I have deliberately shown the ESP8266 as a lower resistance that it would really be (you can expect MΩ) so as to illustrate the problem clearer.

Your R2 now has R(esp) in parallel with it. So the nice clean 20kΩ is now actually (20,000 × 100,000) ÷ (20,000 + 100,000) = 16.66kΩ. That gives us a total of 26.66kΩ, and at 5V that means a current of 0.188mA. Through the 10kΩ resistor we end up with (10,000 * 0.000188) 1.875V dropped. Take that from 5V and you can see that the ESP8266 would only be getting 3.125V.

By reducing the resistors in our network the difference that R(esp) makes to R2 reduces. For instance, reducing it to 1kΩ + 2kΩ gives us an R2 total of (2,000 * 100,000) ÷ (2,000 + 100,000) = 1.96kΩ - hardly any different from the 2kΩ we started with, so the voltage difference will be minimal (3.31 as opposed to the ideal 3.33).

The simple formula for calculating the output voltage from an input voltage and pair of resistors, so you don't have to go long-hand through Ohm's Law every time (though it is useful for understanding exactly what is happening) is:

Vout = R2 ÷ (R1 + R2) × Vin

I can never remember it, though, and usually use an online voltage divider calculator.


My serial Monitor of the Arduino ide does not show up when running Gui? I have created an gui in python using pyserial to communicate with Arduino but my serial monitor does not show up it says (Serial port busy) whenever I run the gui.

The gui works fine but when I want to see the printed data for that, I am using an external LCD but I was wondering if there was a way to see the data in serial monitor. If not could you explain why? I have no idea whatsoever why is this happening.

The problem is simple, you are dealing PySerial using the serial communication port arduino, so you can not communicate with Arduino IDE and python at the same time.

Solution:

In the program you should print python q values you need, with the Print command, so you'll see in the CMD same as you see in the Arduino serial monitor.


Analog Pins are sensing Values I used the example code AnalogReadSerial and tried it on all analog pins from A0 to A7. None of the analog pins were connected to anything so I expectedy to get 0 in the serial monitor. But as it turns out, I was wrong. Only pin A7 shows 0 to 19 values on the serial monitor. The rest have values ranging from 100 to 300 for pins A2, A3, A4, A5 and A6. The worst performers are A1 and A0 with values from 921 to 1023 showing on the serial monitor. What is the cause of this and how will I fix it?

This is normal, as the unconnected pin may float from GND to VCC. You may  enable internal pull-up (to VCC). This is normal for all high-z inputs. If you read digital port you'll see that it floats too. Sometimes you can change digital I/O input value just by waving your hand above the board.

For that reason we always tie high-z inputs to something. You can leave it floating - it won't damage anything, but the value obtained from free-floating input is useless.


avrdude: ser_open(): can't open device "\\.\COM3"? My computer cannot detect my Arduino Uno anymore,

Reset button- > L led light blinks and it turns on forever
Arduino 1.6.5: Tools->Port (greyed out) I remembered that previously it wasn't like this
Unable to upload any sketch codes into the Uno anymore
The existing code uploaded onto the Uno is FastLED(FirstLight) and it will work on my LEDs when I plugged them in

I have tried to .... but none fix my issue

Restart my computer
Press the reset button on the Uno
Using the device mananger to change COM ports
Device manager -> Other devices -> (nothing about Arduino Uno is found here)
Plugged Uno into another computer but still doesn't work
Reinstalled IDE

Problem shown in sketch,

avrdude: ser_open(): can't open device "\.\COM3": The system cannot find the file specified.
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I have experienced a similar issue after plugging in another Arduino device. I didn't set up my environment for a long time and thus forgot he iterates the COM-Index. Maybe this is too easy, but you didn't provide much information.

This solved my problem:
Open Arduino application > Tools > Port > Change to the target Port

If you are unsure which port to choose from: (on Windows)
Open Device Manager > Connections (COM & LPT) > Usb Serial Port (COM[x])
where "[x]" is the index you are looking for.


How to set a not plugged in pin to ground or Low I have digital pin 7 when set to High it does and when set to low it does not.

The only way I can get consistent High or Low is to use a 2 position 3 pin switch with my pin 7 in the middle and ground on one side and 5v on the other.

Is there a way I can use an simple Open/Close switch and still get the same function?

As of not if I dont "pull" pin 7 to ground I get both open and close randomly.

Seems like you already found the solution. Without a pull-down of pull-up resistor, the voltage at pin 7 will float to some random voltage, when the switch is open.

Either add an (external) pull-down resistor. Or flip things around and use the internal pull-up resistor inside the ATMega328p. Then connect the other side of the switch to GND. Whenever the switch is pressed, your digitalWrite gives you a LOW.

To use the internal pull-up use pinMode(7, INPUT_PULLUP);


About ATmega32 event system From my reading on internet i found that the Event system allows peripherals to trigger each other without involving the CPU...does the event system is software or hardware?also does ATmega32 support it? also can any one give me a real application for event system?

The 'old' ATmega 8 bit microcontrollers don't have an event system peripheral. The new "megaAVR 0 series" has an event system. Atmega 4809 on Arduino Uno WiFi Rev2 and on Nano Every is "megaAVR 0-series". The event system of the new ATmegas is similar to SAMD event system I know.

ARM MCUs for example SAMD by Atmel/Microchip used in Arduino Zero and MKR have an event system. Event system is a MCU peripheral. It enables direct communication between peripherals without the involvement of the CPU of the MCU.

The MCU peripherals are what makes the MCU a MCU. Examples of peripherals are GPIO pins, external interrupts, timers, SERCOM, watchdog...

To give you an example of use of the event system. To perform AC phase cutting with a Triac the Triac must be pulsed at right time after zero crossing. (It turns off self at next zero crossing.) To achieve this with MCU, the MCU must sense the input from the zero crossing detection circuit, then start timing the requested off time, then start a pulse to triac's gate and then stop the pulse.

It can be implemented with an external interrupt function for zero crossing, which starts a timer to generate a pulse on a wave output pin.

On ARM MCU it is possible to setup the event system to start the timer on external interrupt over an event, without an interrupt function. Then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals.

After setting up the zero crossing detector input pin for external interrupt without interrupt function and setting up the timer to execute one-shot pulse, the event system will re-trigger the timer on external interrupt.

a simple Arduino SAMD lib for a Triac/ZC module (in development):

#ifndef _TRIAC_LIB_
#define _TRIAC_LIB_

namespace Triac {

const unsigned long AC_WAVE_MICROS = 10000; // at 50 Hz
const int TIMER_PRESCALER = 8;
const unsigned long PULSE_PERIOD = ((F_CPU / 1000000) * 200) / TIMER_PRESCALER;

Tcc* TCC;

void syncTCC() {
  while (TCC->SYNCBUSY.reg & TCC_SYNCBUSY_MASK);
}

void zeroCrossing() {
}

void setup(byte zcPin, byte triacPin) {

  // setup the external interrupt
  attachInterrupt(zcPin, zeroCrossing, RISING);
  uint8_t ulExtInt = g_APinDescription[zcPin].ulExtInt;
  EIC->EVCTRL.reg |= (1 << ulExtInt);// enable event
  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT(1 << ulExtInt); // turn-off interrupt

  const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
  TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
  uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);

  // setup the pin as TCC wave out pin
  PORT->Group[pinDesc.ulPort].PINCFG[pinDesc.ulPin].bit.PMUXEN = 1;
  PORT->Group[pinDesc.ulPort].PMUX[pinDesc.ulPin >> 1].reg |= PORT_PMUX_PMUXE_F;

  // setup the timer

  REG_GCLK_CLKCTRL = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TCC0_TCC1)); // assign clock
  while ( GCLK->STATUS.bit.SYNCBUSY == 1 );

  TCC->CTRLA.bit.SWRST = 1; // reset timer
  syncTCC();
  TCC->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM; // normal PWM as wave output mode
  syncTCC();
  TCC->CTRLBSET.reg = TCC_CTRLBSET_ONESHOT | TCC_CTRLBSET_DIR; //one shot and count down
  syncTCC();

  TCC->PER.reg = ((F_CPU / 1000000) * AC_WAVE_MICROS) / TIMER_PRESCALER; // initial value of period (triac off)
  syncTCC();
  TCC->CC[tcChannel].reg = PULSE_PERIOD; // pin on at compare match and off at 0 (timer counts down)
  syncTCC();

  TCC->EVCTRL.reg |= TCC_EVCTRL_TCEI0 | TCC_EVCTRL_EVACT0_RETRIGGER; // retrigger on event
  syncTCC();
  TCC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV8 | TCC_CTRLA_ENABLE; // set prescaler and enable
  syncTCC();

  // event system
  PM->APBCMASK.reg |= PM_APBCMASK_EVSYS; // power it on
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(EVSYS_GCLK_ID_0) | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN(0); // assign a clock
  while (GCLK->STATUS.bit.SYNCBUSY);

  EVSYS->CTRL.bit.SWRST = 1; // reset
  while(EVSYS->CTRL.bit.SWRST);

  EVSYS->USER.reg = EVSYS_ID_USER_TCC0_EV_0 | EVSYS_USER_CHANNEL(1); // set user TCC0 event 0 on channel 0
  EVSYS->CHANNEL.reg = EVSYS_CHANNEL_CHANNEL(0) | EVSYS_CHANNEL_PATH_ASYNCHRONOUS | // channel 0 is async
      EVSYS_CHANNEL_EDGSEL_FALLING_EDGE | EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_0 + ulExtInt); // source is ext.interrupt
  while (!EVSYS->CHSTATUS.bit.USRRDY0);
}

/*
 * r is from interval <0.0, 1.0>
 */
void setPeriod(float r) {
  unsigned long period = ((F_CPU / 1000000) * ((1.0 - r) * AC_WAVE_MICROS)) / TIMER_PRESCALER;
  TCC->PER.reg = period + PULSE_PERIOD;
  syncTCC();
}

}
#endif

other SAMD example


My Arduino is heating up I am working on a simple Arduino project where I am controlling 5 TowerPro servos. I read that each takes up 2.2 V each so that means the Arduino can only handle about 2 , if using 5V. So far Ive connected 4 with no issues but when I added the 5th the whole thing stopped and the 5V regulator was really hot. That means I don't have enough power and the Arduino is just having a hard time giving not enought volts for all five servos. I just don't know what to do now. Ive tried adding 3  3V battery packs instead of the Arduino but it was smoking. Is there another way to provide the right amount of power for 5 servos without breaking or burning anything!

The voltage regulator on the Arduino is designed to power the logic circuits, and perhaps a few LEDs and other digital devices. It is not designed to power 5 motors.

You haven't specified what current they draw - that is the important question, not the voltage.

As the comments under your question have said, you need to power the motors separately from the Arduino, not through it. However, connect the ground wires, and use the Arduino to control the signal wire to the servos.

The graphic below shows the general idea. For 5 servos even those batteries are probably not enough.

Notice that the power for the motor does not go through the Arduino.


SPST switch - powered from pin output, or voltage regulator I have a SPST switch and I just want to sense whether it's on or not. I will then turn on/off a relay depending on the state of this switch.

The two options I'm considering are: create a digital out on a pin going to one side of the switch, and read the digital in on another pin off the other side of the switch. Or put 5v from my voltage regulator to the switch, and read a digital in off the other side of the switch.

Would a resistor be necessary for the digital in pin with either of these options?

You could configure one of the digital pins as INPUT_PULLUP and connect one end of the switch to it. The other end of the switch goes to ground. LOW = switch ON, HIGH = switch OFF.

const byte pinNumber = 3;

void setup(){
  pinMode(pinNumber, INPUT_PULLUP);
}

void loop(){
}


Is this set up appropriate? Hello Internet Arduino enthusiasts!

I'm totally new to Arduino and as my first project, I'd like to make a controller connected to computer A (the master) and computers B and C as 'slaves'.

The master would simply send commands as USB mouse and USB keyboard inputs to slave computers through an Arduino controller. Think of it as a hardware KVM switch (without the V(ideo)).

Now, I'm planning to work on that during the Christmas vacations, so I need to order the parts now to receive them in time.

I was thinking I could use these parts:

Arduino Due (because it has the capability to send keyboard and mouse input)
2 SparkFun FTDI Basic Breakout - 5V, one for the mouse, one for the keyboard (per target computer) (https://www.sparkfun.com/products/9716) (because I can convert it to a 3.3v, what the Due is using)

Please consider:

The price is not really an issue for now.
I'm not worried to much about the programming.
I'll figure out how to make it work once I have the time and the items.
I know someone who has a starter kit from SparkFun, and there is an electronic store closeby, so I'm not worried about the wires.

Will I be able to make what I'd like with those basic parts, or am I missing something?

Thanks!

You need:

two MCUs that can act as USB devices (one per slave),
some way of getting the commands from the master to the MCUs

That means two Arduino Dues (or Arduino Leonardos, or SparkFun ATmega32U4 breakout boards, etc.) and one USB device of some sort that you can talk to and have send commands to the MCUs.

And perhaps something to transport the commands from the master to the slaves, but you need to think about the programming for that first since the transport and the programming will be very closely connected.


cast from 'char*' to 'char' loses precision Bit of a noob here. Im trying to use the sensor number (float) in my mqtt topic, but cant seem to get this right. Any help would be appreciated. Keep getting this error (cast from 'char*' to 'char' loses precision)

      char buffer2[5];

       dtostrf(sensor.sensor_no, 4, 2, buffer2);
     char* buffer4 = mqtt_topic + char(buffer2);

  dtostrf(sensor.dht22_t,0, 0, buffer);
     client.publish(buffer4, buffer); //Topic name

By adding strings together you are actually adding together the addresses in memory where those strings are.

Instead you need to create a new empty buffer and fill it with the contents of the other strings.

char buffer4[32]; // <-- Enough room for both strings and a NULL character

strcpy(buffer4, mqtt_topic);  // Copy in the first string
strcat(buffer4, buffer2); // concatenate the second string


Using a separate power supply? I'm new to the operation and applications of the arduino and have a question. I would like to run 6 x 4 bit seven segment displays from an arduino controller. How do I connect an external supply to the displays to ensure I don't overload the arduino please?

Regards

Here's a tutorial from Sparkfun that shows how to drive an LED using a transistor to switch the LED. Where the transistor is connected to +5v, that should be to your external 5v supply. The pin labeled "Control" is connected to one of your Arduino pins. Connect the external supply's ground to the Arduino's ground.

Done this way, the Arduino's pin driver only needs to supply enough current to switch the transistor; the current to power the LED is provided by your external power supply.


loading hex code for sd card I am making a game system, and I would like to run code for a sd card over spi. the sd card is set up already. I want to know if there is a way i can put a string of code onto the arduino and run it.

Basically you would like to make a slot loading game system?
You're going to do some research yourself. But I'll do some thinking for you.

Your SD-card should have the compiled HEX code, probably along with some kind of checksum? You should check what your PC sends when you're uploading a program (along with the HEX program).
You're going to need 2 AVR microcontrollers and probably some soldering stuff.
Program the "master" Arduino to read the HEX from the SD card. Then make it add the checksum/things you saw your PC sent along. The master Arduino should reset the other ("slave") arduino before sending, just like the PC does, this is done in hardware, and you'll have to wire into the reset button.

I'm not sure if this would work at all. It just sounds like the only possible way.

Alternatively the parallax propellor has a possibility for self-modifying code, along with VGA graphics. This might be a better shot, it's architecture fits better to your project. And I believe there are some similiar projects with the propellor, though I'm not sure about the SD-card.


output of yun is not 3.3 After execute the program of below, the 13 pin output is 4.8v. Why it's not 3.3v?

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

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(13, HIGH);
}

The Atheros chip on the Yún is run off 3.3V, but the AVR chip, which is what is connected to the external pins, runs off 5V. What you are seeing is normal (a bit low though, but within spec).


Which type of Motor Drivers to drive Unipolar Stepper Motors? I hope this question is specific enough. Basically I want to know if it matters a great deal what kind of Motor Driver IC(s) or pre-assembled kits you use to drive a Unipolar Stepper Motor.

For example: Can the following Driver be used to control this Stepper Motor?

Driver: https://www.sparkfun.com/products/9670

Motor: http://www.jaycar.com.au/productView.asp?ID=YM2754

Thanks!

It does matter.  There are pros and cons to each different driver setup.

If you wire the motor as a bipolar, which I'm not sure that you can, you can use the driver that you linked, but it is not very good for driving stepper motors.  https://www.sparkfun.com/products/11876 is a better driver for steppers for half the price.  (still have to wire it bipolar)

If you need to stick with unipolar wiring, PCBheaven.com shows an example using a CD4017, MOSFETs, and diodes to run a unipolar motor.  It will only turn one direction.  Instead you could use a micro-controller, such as an Arduino, in place of the CD4017 along with logic-level MOSFETs to go both directions.

A tutorial on the Arduino site uses a ULN2003A, which is not powerful enough to drive your motor to its full potential (does it need to turn, or turn well?) and doesn't have the diodes (important to protect your IC!), but the Arduino sketches would still work using the schematic from PCBheaven.

A couple of complete driver boards:

UNIPOLAR STEPPER MOTOR DRIVER

FANCY UNIPOLAR STEPPER MOTOR DRIVER


Arduino Shield on Breadboard I would like to ask if I can stack directly Adafruit PN532 RFID Shield onto my breadboard. Or do I need something for that? Thank you.

Chances are the offset headers won't allow the shield to directly plug into a breadboard.

As @Majenko noted, shields have a header that is offset by 0.16" from the other headers. Since a breadboard is a strict 0.1" grid that header won't fit into the holes.


Where are the chip configurations stored in IDE 1.6.x? How to modify them? With the new 1.6.x version of the Arduino IDE, obscurity of adding new chips has gained new level. It now seems you have to add HTTP links to some JSON files in single-line edit field in settings.

I did so and to add AtTiny to Arduino IDE, I used this JSON file: https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json

I have AtTiny 13 however. It's same as the others, according to datasheet, but has different signature:

avrdude: Expected signature for ATtiny45 is 1E 92 06
         Double check chip, or use -F to override this check.
Wrong microcontroller found.  Did you select the right board from the Tools > Board menu?

I tried to search ATTiny45 and the signature over the files - no success.

What I need is to add the ATTiny13 to the list so that I can finally actually do some programming, instead of being completely helpless.

You are importing a json file provided by someone for free.
The best thing you can do is contribute by adding ATTiny13 to this repository.
To do so:
So go to github (create a account if you do not have one);
create a fork of the repository.
Add your ATTiny13 board to the boards.txt file.
mod the json file to contain a new version and the attiny13.
Test and if everything works fine
Create a pull request


Problem with sending IR with at ATMega328P-PU I have a sketch that sends an IR code every second. It works fine (the correct code is received by my receiving Arduino next to it) on the Arduino but when I try to move the sketch to an ATMega328P-PU, the IR no longer sends (the serial monitor output still works).
I have used a camera to look at the IR LED and it just doesn't flash on the ATMega328 but does on the Arduino (and I have tested my LED, it does work). It uses pin 3 on the Arduino, so I use pin 5 on the ATMega328.
Are there extra components that are needed to make PWM work without the Arduino board? I am honestly stumped so any help would be appreciated. Thanks in advance.
Sketch:
#include <IRremote.h>

IRsend irsend; //Setup the IR transmitter

int codeToSend;
int team = 1;
int damage = 0;

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

void loop()
{
    team++;
    if (team > 8) team = 1;
    damage++;
    if (damage > 99) damage = 0;

    if (damage > 9) codeToSend = (String(team) + String(damage)).toInt();
    else codeToSend = (String(team) + "0" + String(damage)).toInt();

    Serial.println("sent");
    irsend.sendNEC(codeToSend, 32);
    delay(500);
}

NOTE: The following comment was left on this answer (below) and indicates the principal problem the original poster was having above and beyond not having a resistor, etc.

SOLVED - my breadboard was broken on that rail. :/

Current limiting
What you have pictured looks alright for the most part with the exception of there appearing to be no current limiting resistor for the IRED.  It is possible that you've damaged the IRED by setting the pin HIGH for an extended period of time.  It is also technically possible to have damaged the AVR (or just the one pin) by doing that, though this wouldn't be my first guess.
Typical forward voltages for an IRED around around a volt.  An AVR pin's maximum rating current is 40mA.  To get proper logical levels out of it, it should be less than 20mA.  You could perhaps operate near 30mA, since you're not doing much else with the AVR's ports and you're not trying to get logic level voltages out of the pin.  For that you'd need a resistor in series with the IRED that is something like  (5V - 1V) / 0.030A, approximately 133 ohms.

Transistors
When people use IRED to make remotes, it is normal to use a transistor to offload the current requirement from the MCU.  And also to operate the IRED above its continuous operation current, closer to it's rated peak/pulse current.  Operating in the low tens of mA often only gets you a meter or so.
That arrangement might look something like the following for higher current pulses around 80mA:

Asides

I'm not able to read your reset resistor well.  If you're not, do measure it to make sure it's 10K.  If in doubt, remove it.  There is a weaker internal pullup on the AVR reset and it's usually enough.  If you wanted you could wire the reset signal over to the UNO reset pin to take advantage of the external pullup, reset switch, and DTR reset mechanism of the UNO itself.

You may want to add .1uF capacitors from your VCC and AVCC pins to ground.  You can often go without while experimenting, but when you're switching higher currents they'll become more important.

I have a bunch of those jumpers with the rounded (cylindrical) ends.  They often don't make good connections on breadboard.  You can save some trouble sometimes with "Dupont" type jumpers or just making your own out of solid 22awg hookup wire.


RadioHead and Servo compile problems I am having this problem when trying to compile my sketch. I am using RF frequency modules to send data between devices and a servo motor to control the tilt of a ramp. I understand that both libraries use TIMER 1 but I am unsure how to change one of them to use TIMER 2 thanks.

Arduino: 1.8.7 (Windows 10), Board: "Arduino/Genuino Uno"

libraries\Servo\avr\Servo.cpp.o (symbol from plugin): In function `ServoCount':

(.text+0x0): multiple definition of `__vector_11'

libraries\RadioHead\RH_ASK.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.
Board at COM4 is not available

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

You can force the RadioHead library to use Timer 2 instead. This can be done by enabling the define RH_ASK_ARDUINO_USE_TIMER2 near the top of RH_ASK.cpp.

More details about how to do this may be found in the RadioHead library documentation. Please see https://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html.

Cheers!


how to prevent IR signal to go through 3d printed plastic? I'm working on two arduino (one a dock, the other one on a robot) communicating through a IR to let the latter know about its location.

I 3D printed a piece which goal was to channel the 3 IR led lights, to prevent them from overlapsing (exactly in the same manner as the Kobuki.

For a reason I don't know, the IR signals seem to go through  the 3D printed piece which doesn't seem to let visible light through.

I known that there is no 100% absorbant materials, and I know "black for visible lights" doesn't necessarily mean "black for IR lights".

I think my problem is more related to my lack of experience in the field. My question is : why do I get signals from a IR led channeled toward a location I am not in ?

Patently, it means my light channels are not channeling light.

Therefore, better : How can I make a better (and cheap) channel for IR light ?

The piece I 3D printed is grey (silvery like I guess)

edit : to prevent incomprehension, i would like to clarify "channel". What I mean is to block all light "not going" in the right direction, whatever happens to that light. I apologize if it is not the word I should have used.

You can not use common modulation remote control receivers as they contain an ACG feature which will likely "turn up the volume" until it detects even a weak reflected signal.  Instead consider if this reflective sensor, which does not contain an AGC feature, is appropriate for your design.

Alternatively you might explore the response time of the AGC feature to see if you can defeat its intended purpose.  That is to say, rapidly switch between IR transmitters in order to keep the AGC level at low gain.  Essentially blinding it from weak reflected signals.

You might also transmit continuously on all IR sources and determine if the AGC will put the weak signals below the noise floor.


LCD is not showing any text I'm using LCD QC1602A with a 10k potentiometer and changing contrast. It works well but the problem is that no text is appearing.

I'm using the LCD hello world examples and a few other examples. I tried reconnecting wires at least 5 times but every time it's the same problem. I connected it like this but the screen is not displaying any text at any contrast.

PS: It was showing white squares only in the top row, and now it's in both rows.

Two rows of white squares means that the driver chip has been successfully initialised to run in a 2x16 mode (it defaults to 1x16 which was the 1 row of squares you had originally).

So that means that you are configuring the display at least partially correctly.

You should adjust the pot so that you can just about see the squares. The squares are the background and the text would appear over them. If they are too bright you won't see the text. So adjust the contrast until you can just see that there are squares there.

If the wiring is correct and the code is correct then you should be able to see the text.


Is it possible to compile and upload code witout the IDE? I just got started with Arduino, and found out that I need the IDE to compile and upload codes, which works perfectly fine. This is my code:
# pragma GCC optimize ("Ofast")

char i = 0 ;
unsigned long time, lastTime ;

void setup() {
    pinMode(LED_BUILTIN, OUTPUT) ;
}

void loop() {
    time = millis() ;

    if (time > lastTime) {
        lastTime = time + 100 ;
        i = ~i ;
        digitalWrite(LED_BUILTIN, i  ? HIGH : LOW) ;
    }
}

But the biggest problem is that the IDE is written in Java and it uses 1 GB of system's memory, and it's very heavy.
So is there a way I can use the Linux command line to compile and upload the code to the Arduino UNO?

Yes, I haven't used it but on the official page it is mentioned, called Arduino CLI (command line interface), available for Mac and Linux.
https://www.arduino.cc/pro/cli
Excerpt:

Arduino CLI is a command line tool that contains all you need to
easily build applications around the Arduino ecosystem. Parse the JSON
output of the CLI or implement it as an always-on service that accepts
commands via a gRPC interface using your language of choice.
Arduino CLI is the backbone of the Arduino Create Web Editor serving
over a million users.

Also, it's open source and can be found on GitHub at https://github.com/arduino/arduino-cli/releases


Arduino Yun, node.js and serial I'm trying to bypass Bridge library and read serial directly from nodejs. I'm on the last sys upgrade (1.3) I have correctly installed nodes and serial module via opkg install. I have also commented out the line in the /etc/inittab:

#ttyATH0::askfirst:/bin/ash --login

This is my arduino code:

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

void loop() {
  Serial.println("dudee");
  delay(100);
}

This is my node.js code:

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyATH0", {
    baudrate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
}, false);

console.log("hello");

serialPort.on("open", function () {
    console.log('open');
    serialPort.on('data', function(data) {
        console.log('data received: ' + data);
    });
});

serialPort.on('error', function(err) {
    console.log('error: '+err);
});

serialPort.open();

If I ssh to yun and run the script I don't see any "dudee":

~/test# node serial.js
hello
open

While if I open the serial monitor I see it.

If I run the node script on my computer (changing the right serial port name) everything works nice and I see the dude..

What can it be?

Autosolved thanks to this old forum post.

It is Serial1 not Serial.
In the Arduino code in the Yun Serial is a different object from Serial1. Even if it is not super well document (or at least not in the first dumb google search) here are some links that talks about Serial1:

https://www.arduino.cc/en/Tutorial/YunSerialTerminal
http://andrea-toscano.com/arduino-yun-tcpip-to-serial1-redirect/
http://crossbar.io/iotcookbook/Arduino-Yun-Disable-Bridge/


Bluetooth module as MCU? Can I use Bluetooth Low energy devices as micro controllers directly instead of communicating to Arduino e.g. HM-10/11 or even HC-05/06 ? If so what are limitations e.g. can  I hook sensors or control other stuff like LEDs or transistors with PWM ?

I have built a motion sensor, which consists of Arduino, Bluetooth Low energy HM-11, battery and sensor itself. It worked just fine, but one guy told me that Arduino may be completely unnecessary and that Bluetooth module could replace its functionality !
I then started digging for information, and either it's impossible or I am terrible at googling. Everything I found was info about some kind of development kits for HM-10/11, also pin outs of those boards. They do have some IO pins, which can mean it's possible, but I found no tutorials nor examples on how to program those boards and use with other components.

All bluetooth modules will need some sort of mcu to handle the requirements of the protocol stack, and it seems common that there will be at least a couple of GPIO which can be used directly if your sensor requirements are simple. At the other end of the spectrum, you will find there are also mcus with a full set of peripherals - enough to support a couple of sensors and a small display for example. Remember, the wearables market is likely bigger than the hobby electronics market.

Limitations are most likely to be in the area of ease of use (as you hint at with your question), and possibly the toolchain which you would need to use (unlikely to be arduino compatible). Also, the bluetooth stack typically takes a reasonable proportion of these wearables focused devices, so there is not a big amount of ram/flash or CPU cycles to spare even if you opt for a part which is more than 'just' a serial-to-bluetooth bridge.


How to extract the binary from STM32 MCU I have an already programmed STM32MCU. But I don't have the source code. I understand it is difficult to get the source code from the IC. I have heard some people can get the binary file from the IC which I can flash to another Arduino. Any guide or material will be helpful. I tried my luck with google. but didn't find any good resources on this matter.

you can download the flash content using a ST-Link probe and STM32CubeProg tool. you can't flash it to just "any" arduino board; it must be the exact same chip or same family MCU, if the IOs and peripherals used are the same.


A recommendation for a fast-response-time-resolution-mp3-module for arduino I am working with Arduino which activates a box which is similar to a Skinner Box. Some of the output sound stimuli are sine waves with duration of less then 5 milliseconds. I output the sounds using the MP3 module DFR0299.

However there are too much problems using this module: it seems like the module has a wakening delay of around 100 ms, so it is not working well with this duration and below (the response time of the module is important).

So, I was thinking of buying a better module. However, I am far from being an expert in these things..

I can look for other modules in the internet, but, just from looking at the datasheets, I cant tell if the quality of the module is what I need.

I would be grateful if any of you could give me names of modules that might feet my requirements (or even advice me at what to look in the datasheets)

Thanks!

I'm going to suggest that you stay away from these mp3 modules. It is perfectly reasonable to use a stand-alone arduino unit to directly generate sound using the digital output pins with a low-pass filter RC circuit. This is the most efficient way of doing this and will give you a very low activation latency.

https://playground.arduino.cc/Code/PwmFrequency/

The other option is to connect a DAC circuit and simply build a sample table for the wave outputs you need for each tone.


Difference between print() and println() What is the difference between print( ) and println( )?
I see none when I run a code.

An easy way to see the difference is using Serial.print();/Serial.println();.

print();

will print out whatever you input wherever the cursor currently is. For example:

Serial.print("Test");
Serial.print("Words");

This will print:

TestWords_

The underscore marks where the cursor is (and therefore where the next print command will start). In contrast, the code:

Serial.println("Test");
Serial.println("Words");

will print the following:

Test
Words
_

You can also print multiple statements and then follow with println like so (note the space at the end/beginning of the strings):

Serial.print("These ");
Serial.print("Test");
Serial.println(" Words.");

to get the following output:

These Test Words.
_

You can also use println(); to add a newline character in general. If you would print a variable that doesn't return a newline character, println(); can be used for formatting. Example:

int x = 50;
Serial.print(x);
Serial.println();

This will print:

50
_

Finally, you can add in special characters like a tab \t inside your quotes for formatting. Example:

Serial.println("Test\tTest")

This will return:

Test    Test
_


Read serial data from XV11 sensor I am trying to read data from an XV-11 sensor using the description of the format found here https://xv11hacking.wikispaces.com/LIDAR+Sensor.  This is the code I am currently using to communicate with the computer by USB and the sensor with software serial on an arduino uno.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  mySerial.begin(115200);
}

int count = 0;

void loop()
{
    if(mySerial.available())
    {
      byte in = mySerial.read();
      Serial.println(in, HEX);
    }
}

However, the data I am receiving on the computer is inconsistent with what I expect.  For example, I am expecting a 0xFA byte every 22 bytes, however this only sometimes happens.  Many times extra or fewer bytes appear in the middle of the data.  I am using the 5 volt arduino serial communication, however I have heard that it is still compatible with 3.3 V sensor communication, so I doubt it is the problem.  I don't thinkthe sensor is broken, as it is new from a working unit.

Soft Serial is totally unreliable. You may have a better error rate at other baud rates, but you will never achieve the same as a hardware based serial connection.  I'd switch my debugging connection to the software serial, nd use the hardware serial for the XV-11.


How to increase the detection distance on Arduino KY-032 obstacle Avoidance sensor? We've got an Arduino KY-032 obstacle avoidance sensor, and have spent a decent time searching and researching to find a detailed data sheet/manual to figure out how it works; but there aren't any detailed information on the module.

One of the few instructions here says that the potentiometers on the chip are used to adjust the distance, but I've tried all different settings and the maximum I can get is 10 centimeters. I've tried different surfaces with different reflectivity levels, but it doesn't really differ much.

Any idea how to increase the distance on this? Anything to do with the enable jumper?

Update: Here's the related code to the obstacle detection:

void loop() {
  // check the network connection once every 10 seconds:
  val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 3 to read val
  if(full==1 && val==LOW) {
    Serial.print("Bin Full");
    delay(5000);
  } else {
    if (val == LOW) {
      // When the obstacle avoidance sensor detects a signal, LED flashes
      digitalWrite (Led, HIGH);
      delay(2000);
      if(digitalRead(buttonpin)==LOW) {
        delay(2000);
        if(digitalRead(buttonpin)==LOW) {
          full = 1;
        }
      }
      count++;
      //printCurrentNet();
      sendData();
    } else {
      digitalWrite (Led, LOW);
      if(full==1) {
          count = 0;
      }
      full = 0;
    }
  }
}

The wizecode page has some nice info. However the R5 pot (near the EN jumper) does not change the duty cycle but directly the current to the IR LED - still affects the brightness though. Too much current seems to trigger false positives - depends on your additional optical shielding. I put some black heat shrink tubing over the sensor - with a hole punched in for the sensor to see though.
Also the R6 pot does not really "fine tune" the frequency, more like "coarse tune" - even a small nudge can detune by a kHz, greatly reducing the sensitivity.
If you use the EN jumper, a suddenly appearing object gives a short pulse, but then the disturbance signal suppression kicks in turns sensitivity down and 'unsees' the object. Also slowly appearing objects are not recognized for that reason. Only very near objects (a few cm) give a strong enough signal to overcome that sensitivity attenuation.
What I found somewhat irritating: Setting EN to LOW lets the IR LED steady on instead of off, which I would have expected. That might irritate the sensor more than necessary. Also draws more power (maybe even a lot, depending on R5 current setting).
Funny enough, you can get a somewhat analog behaviour from this sensor if you measure how long it takes from activating the EN pin to the sensor output getting low. The nearer the object is, the faster it reacts. Near objects take ~190us, farther objects more than 400us. Not nearly a linear behaviour though. Also depends on distance, size, angle, IR reflectivity and IR LED power.
However it can detect a person in more than 1m distance.


Arduino Newbie: Solderless Breadboard Alternate I am completely new to arduino. I have created a circuit using solderless breadboard. But obviously the connections are lose or not as good as a soldered solution. So I was wondering since I am new to circuits too, what is the easiest

Breadboards are for development and testing. When you are OK with your circuit, then you solder it.

Your alternatives:

Point-to-Point

Just solder directly component to component. You can arrange your component for minimal space and minimal wiring length. Can be very elegant (depends on your abilities) and doesn't require any board.

Perforated board

For personal projects, you can use a perforated board to put all your components. Requires some planning in components placement and wiring (you can paint yourself in a corner). Easy to do.

Expansion Shield

It's a perforated board on a shield, so you just plug it over your Arduino Uno. Great if you need easy access to lots of Arduino pins. Cons: little space for components. There are versions with a mini-breadboard instead of a perforated board.

PCB

You can make your how PCB, but it's hard and too much work. Use it only for high volume production. It require lots of preparation and dangerous chemicals.

Useful links (YouTube)

Review of some prototype circuit building methods
Perfboard Prototyping
Breadboards & Perfboards


How to use a grove speaker without using delayMicroseconds? is there another way to replace delayMicroseconds(BassTab[note_index]) as I cannot have delays in my loop due to the need of having multi-tasking in my sketch.

Grove speaker: http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html

/*macro definition of Speaker pin*/
#define SPEAKER 8

int BassTab[]={1911,1702,1516,1431,1275,1136,1012};//bass 1~7

void setup()
{
  pinMode(SPEAKER,OUTPUT);
  digitalWrite(SPEAKER,LOW);
}
void loop()
{
    sound(5);
    delay(5000); //Wait 5second and play the sound again
}

void sound(uint8_t note_index)
{
  for(int i=0;i<100;i++)
  {
    digitalWrite(SPEAKER,HIGH);
    delayMicroseconds(BassTab[note_index]);
    digitalWrite(SPEAKER,LOW);
    delayMicroseconds(BassTab[note_index]);
  }
}

It's just a small amplifier and speaker - what you put into the SIG pin gets amplified and sent out the speaker.

Instead of doing the audio generation manually like that I would suggest using the tone() function which will generate an audio tone at a desired frequency in the background.

https://www.arduino.cc/en/Reference/Tone


LEDs effects changing with a button So I have a bunch of functions (methods) made and I want to make it so that if the button is clicked (single click) the effects to change... I thought something like:

buttonState = digitalRead(buttonPin);
if(buttonState==HIGH) {
  counter++;
  if(counter>2) {
    counter=0;
   }
 }
if(counter==0) {
  Foo1();
}
if(counter==1) {
  Foo2();
}
if(counter==2) {
  Foo3();
}

But I noticed that it will only read the input button(buttonPin) if I click the button in the exact time (when the function has already ended and at digitalRead time)... So is there some way to do it even if the function is in progress to cancel it and go to the other ones (some way that the digitalRead will read it non stop)?

I think you want to look at interrupts.  You are right, unless the button happens to be pressed when you read the state of it you won't see it as pressed.  If you foos take a long time to execute the you will miss button presses.

What you can do is use 'interrupts'.  Certain pins can be configured to stop the main program and run a small bit of code (that can't do certain things).  For instance they can change the value of a global volatile variable.  Next time the program reads the variable it will read the new value (volatile prevents the value being cached by the processor).

With you current code, you would remove the digital read line, and the if (buttonState == HIGH) block and move those into you ISR.  This would mean every click would be counted.  If you wanted the ISR to stop the current foo and move on then you foos would need to check a flag that the ISR also set and when they see it they return.

In the ISR you can't call Serial.print() etc, it takes too long and your ISR won't work.  Keep it fast and small.

https://www.arduino.cc/en/Reference/AttachInterrupt
https://www.arduino.cc/en/Reference/DetachInterrupt


TimerOne Library - Response time I'm trying to write a library for (rather slow) communication with visible light and have recently tried to include the TimerOne library as a timer.
I want to send bits at 2kHz, so with a period of 500µs. I'm initializing the Timer1 with 500(µs) like this and then attach an interrupt to it to call my transmit function:

Timer1.initialize(500);
Timer1.attachInterrupt(transmitBit);

However, when I try to measure the period with a logic analyzer, it tells me that there is actually a period of 2,000µs. Could this be due to some overhead created by the library? Where else could the problem be?

If you need any other information just let me know and I'll try to provide it.

Thanks in advance for your feedback.

EDIT: I've just tried adding the period as a parameter to the attachInterrupt like so:

Timer1.attachInterrupt(transmitBit, 500);

And now I'm measuring a period of 30µs for whatever reason? Can anyone explain me what's going on?

EDIT: This is the rest of my (relevant) code:

Transmitter::Transmitter()
{
  [...]
  Timer1.initialize(500);
}

Transmitter* Transmitter::_instance;

void Transmitter::start() {
  _instance = this;
  Timer1.attachInterrupt(_transmitBit, 500);
  _active = true;
}

static void Transmitter::_transmitBit() {
  _instance->transmitBit();
}

void Transmitter::transmitBit() {
  if(_active) {
    //Preperation
    if(!_manHalf) { //only change the state when the manchester bit is completely transmitted.
      if(_busy) {
        //Serial.println("Transmitting!");
        /** if there is currently a transmission running
          * read the next bit from the frame
          */
        _state = *(_frame + _pos);
        if(_pos >= _frameSize) {
          _busy = false;
          _state = 0;
          _pos = 0;
        }
        _pos++;
      } else { //else transmit the idle pattern
        _state = 0;
      }
    }
    //Transmission
    if (!_manHalf) {
      digitalWrite(_pin, !_state);
    } else {
      digitalWrite(_pin, _state);
    }
    _manHalf = !_manHalf;
  } else {
    digitalWrite(_pin, HIGH);
  }
}

Before using libraries, try to see whether you can manipulate the timer registers directly to achieve what you want.  You may find it is easier!

In the following example I assume you are using an ATmega328 chip.  The code may be slightly different for other microcontrollers.  In that case you can read the data sheets for both microcontrollers and work out what you need to change.

I also assume the data you want to transmit is stored in a byte array.  Initialize the data how you prefer.

e.g: byte my_data[10] = {0,0,0,0,0,0,0,0,0,0};

Next, you want to initialize timer1 in the main loop

TCCR1A=0;
TCCR1B=0;

To send data at 2000 bits per second, the following settings can be used

ICR1=124; // Timer counter resets to 0 after reaching 124
OCR1A=125;
OCR1B=125; // other counter match registers must be higher than ICR1
TCCR1A=B00000010; // waveform generation mode 14, fast PWM, ICR1=top
TCCR1B=B00011011; // clock scaler 64, 1 count = 4 us.  125*4 us = 500 us
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags

This will set the timer1 match register bit ICF1 every 500 us.  There are several ways of using the timer to send the data.  My preference would be to poll the match flag.  The timing precision is about as good as you can get - a couple of clock cycles:

loop_until_bit_is_set(TIFR1,ICF1); // wait until TCNT1=ICR1
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // clear match flags
// switch digital output high or low depending on data bit to be sent

One way is to run a state machine loop like this:

unsigned int state;

void setup(){
state=0;
}

void loop(){
switch (state){
case 0: // idle or receiving data to be sent
TCCR1A=0;
TCCR1B=0;
// insert other code here
// conditional function, when message data received, set state=1;
break;

case 1: // setup timer
ICR1=124; // Timer counter resets to 0 after reaching 124
OCR1A=125;
OCR1B=125; // other counter match registers must be higher than ICR1
TCCR1A=B00000010; // waveform generation mode 14, fast PWM, ICR1=top
TCCR1B=B00011011; // clock scaler 64, 1 count = 4 us.  125*4 us = 500 us
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
state=2;
break;

case 2:
loop_until_bit_is_set(TIFR1,ICF1); // wait until TCNT1==ICR1
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // clear match flags
// switch digital output high or low depending on data bit to be sent

// add conditional function so that when you are finished sending data, reset to state=0;
break;

}
}

As always, please upvote if you find this helpful.


How to control an Arduino connected device accross the Internet? Actually i am trying to do IoT based work.

Until now the sensed data(temperature and humidity) has been made available to only for one user on the Internet using Apache tomcat. So far we have just created a one way communication link between the sensor node and the Internet through the PC.

Now I need to control a device (say a fan) according to the variation with sensed temperature from anywhere through the internet. For the HTML I have used Java Script, which I am new to.

Perhaps a message brokering service like MQTT is what you are looking for. Far too much to it to explain it all here, but basically it lets you publish messages and subscribe for messages, over a network.


error: expected primary-expression before ',' token edit status 1 Im using tinkercad for my robotics class and I can't seem to figure out a solution for this problem.
Heres my codes:
#include <LiquidCrystal.h> //LCD library
#define echo 2
#define trig 3

// Gas Sensor
#define GREEN 4
#define Yellow 6
#define RED 7
#define Buzzer 5
#define Sensor A0

float duration;
float distance;

LiquidCrystal lcd(13,,12,11,10,9,8);

int sensor_Input;
float temp;

void setup()
{
  // Ultrasonic sensor
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  Serial.begin(9600);
  lcd.begin(13, 2);

  //temp
  measure_Temp();
  display_Temp();

  // Gas Sensor
  for (int i = 0; i < 6; i++)
    pinMode(i, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  // Ultrasonic Sensor
  time_Measurement();
  distance = duration * (0.0343) /2;

  display_distance();

  // Gas Sensor
  for (int i = 0; i < 6; i++)
    digitalWrite(i, LOW);

  status_Indicator();
}

void status_Indicator()
{
  // Gas Sensor
  int sensor_In = analogRead(A0);
  Serial.println(sensor_In);

  if ( sensor_In>=40 )
  {
    digitalWrite(RED, HIGH);
    digitalWrite(Buzzer, HIGH);
  }
  else if (sensor_In >=25 )
  {
    digitalWrite(Yellow, HIGH);
  }
  else
  {
    digitalWrite(GREEN, HIGH);
  }
  delay(10);
}

void time_Measurement()
{
  // Ultrasonic Sensor
  digitalWrite(trig, LOW);
  delayMicroseconds(2);

  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);

  duration = pulseIn(echo, HIGH);
}

void display_distance()
{
  lcd.clear();
    lcd.setCursor(0, 0);
  Serial.print("Distance in m: ");
  Serial.print(distance);
  Serial.println();
  lcd.print("distance in m: ");
  lcd.setCursor(5, 1);
  lcd.print(distance);
  delay(1000);
}

void measure_Temp()
{
  //Temp
  sensor_Input = analogRead(A0);
  temp = (float)sensor_Input / 1024;
  temp = temp *5;
  temp = temp - 0.5;
  temp = temp *100;
}

void display_Temp()
{
  //temp
  lcd.setCursor(0, 0);
  Serial.print("Temp. in Celcius: ");
  Serial.print(temp);
  Serial.println();
  lcd.print("Temp. in Celcius: ");
  lcd.setCursor(5, 1);
  lcd.print(temp);
  delay(500);
}

You have two commas in the command when making the lcd object:
LiquidCrystal lcd(13,,12,11,10,9,8);

Probably just a typo, delete the comma and you should be good to go.
LiquidCrystal lcd(13,12,11,10,9,8);


Frequency will not change I am working on a project where I am trying to get an input signal filtered according to its frequency. I checked the signal before it went into my DSP algorithm to see where the problem was and I found that the frequency was remaining the same no matter if I put in 30Hz 120Hz or 58kHz. This leads me to think I have a problem with the sampling rate. Does that sound like it is the actual issue? Or am I barking up the wrong tree?

I was just using the readADC command to read in the data

void setup()          //Setup Function to intialise ADC and Serial Communication
{
DDRC=0x00;            //PORTC as INPUT
DDRD=0xFF;            //PORTD is OUTPUT
DDRD=0xFF;
for(i=0;i<N;i++)
  {
    InitADC();
    a=ReadADC(4);
    x[i]=a;
  }
  Serial.begin(9600);
}

I am not sure how you are sampling the frequency because you have not shown us your code.

At work we use a ATMega328P to sample frequency. This is done in 2 different ways:

We use the pin that counts (using an internal counter) every time it transitions (ie from low to high and from high to low). After 1 second that counter is read and then that counter is cleared. With the number read in, it is divided by 2 to get the frequency.
We use another pin that counts every time it transitions from low to high. From memory the counter is not very large so we count the number of times it overflows. When the 1 second interrupt fires we multiply out the number of overflows by the counters capacity. Lastly the remainder from the counter is added to the result to get the frequency. Again the counter is cleared.

The above examples use the AVR's internal counters. A less efficient way of getting the frequency is to have an interrupt to count the number of times a pin changes. Again this can be read and reset at one second intervals. This slows the overall execution of the program down when very high frequencies ( > 40K Hz) are being presented on the input.


strange behaviour of dtostrf() I'm trying to program a little bit in Arduino, but I'm stuck with probably something trivial.

This is what I have:

char ang[3], lat[9];
dtostrf(GPS.angle, 3, 0, ang);
dtostrf(GPS.latitude, 9,5, lat);

Serial.println(lat);
Serial.println(ang);
Serial.println("-------");

I would expect the following in the serial monitor:

5111.60160
267
-------

But instead, I'm getting this:

5111.60160
2675111.60160
-------

So it looks like the ang holds both the angle and the latitude....

Why is this happening? And how can I solve this?

My goal is to make one big string, comma separated, from the data stored in GPS

Your arrays are both too short for the strings they're meant to hold. In particular, ang has three digits and only three bytes. The string-terminator, NUL, ends up in the 1st byte of lat. Since you generated the ang string first, lat over-wrote ang's NUL character, effectively getting appended to ang.

The lat string will need at least (10+1) bytes; ang will need (3+1) bytes, counting only the actual data in your question.

I make it a habit to declare string arrays just as I wrote the sums above, to make it clear that I've counted both the contents and the NUL byte, so:

  char ang[3+1], lat[10+1];

I doubt that you need to specifically add the NUL terminator; it would quite unusual (counter-conventional) for a C/C++ function that generates a string to leave off the terminator (except in a few special cases).

Try increasing just your array sizes first; it'll probably work.


Memory organisation of MIFARE 1K I'm trying to use a MIFARE 1K RFID card with RC522 RFID reader/writer for my college project.
I'm trying to understand about memory organization of MIFARE 1K.A documentation() that supplied with a RFID Arduino library() says like this.
I will very appreciate if someone explain me this portion clearly.

  The MIFARE Classic 1K offers 1024 bytes of data storage, split into 16 sectors; each sector is protected by two different keys, called A and B. Each key can be
  programmed to allow operations such as reading, writing, increasing valueblocks,
  etc. MIFARE Classic 4K offers 4096 bytes split into forty sectors, of which 32 are same size as in the 1K with eight more that are quadruple size sectors. MIFARE Classic mini offers 320 bytes split into five sectors.
  For each of these card types, 16 bytes per sector are reserved for the keys and access conditions and can not normally be used for user data. Also, the very first 16 bytes contain the serial number of the card and certain other manufacturer data and are read only. That brings the net storage capacity of these cards down to 752 bytes for MIFARE Classic 1k, 3440 bytes for MIFARE Classic 4k, and 224 bytes for Mini. It uses an NXP proprietary security protocol (Crypto-1) for authentication and ciphering.

Accordind to above quote,

  For each of these card types, 16 bytes per sector are reserved for the keys and access conditions and can not normally be used for user data.
  Blockquote

Explain how to divide 1024 bytes like this.It has 16 sectors.So,total memory should be 16*16=256 bytes.This is impossible. Please explain this.

You're reading (and doing your sums) backwards.

You have 1024 bytes of data space.

That data space is split into 16 sectors, so 1024 / 16 = 64 bytes per sector.

Each sector has 16 bytes reserved for keys etc, so each sector has 64 - 16 = 48 bytes of user data space.

48 bytes of user data space per sector multiplied by 16 sectors is 768 bytes.

Incidentally 1024 - 768 = 256, which is what you were calculating before.  What you calculated was the amount of the 1024 bytes that is reserved in total for the keys and access controls.


Why can I power an SD card reader from a digital pin? I'm trying to understand the power requirements of an SD card. I have a cheap breakout board from eBay that includes built-in level shifters, so I can plug it in directly to my Arduino. I provide power from one of the digital pins, and it works. This doesn't make sense to me, as I thought an SD card reader should draw upwards of 50-100 mA, well over the capacity of an individual digital pin on the Arduino. However, at least one SD card manufacturer does this as well, so I'm not making this up.

I have checked, and the data is written no problem. I have connected an ammeter between the Arduino and the SD reader, and it never jumps above 3 mA? The only problem I have is when I switch from using the USB cable (connected to my computer) for power to a battery pack, the SD card starts acting erratically. Which makes sense, if it's not getting enough current.

What I'm wondering is why it ever works when connected to a digital output pin? Clearly I'm missing something important.

Edit: The reason why I thought they required a lot of current: I've seen comments like this on a number of tutorials:

  One is that they are strictly 3.3V devices and the power draw when writing to the card can be fairly high, up to 100mA (or more)!

Edit2: @dlu answer lead me to investigate the voltage I was sending to the SD card reader, which turns out to have been the problem. I was supplying the Vin pin with 5.2V, which was regulated down to 4V, presumably too low for the 5V-3.3V step-down at the SD card. Moving the battery power to the 5V pin corrected this. This also introduces some new risk, as the board is now receiving unregulated power. But that is another problem.

Edit3: And finally, answering my original question: I found a note on the Adafruit product page for a similar breakout that indicates:

  Onboard 5v->3v regulator provides 150mA for power-hungry cards

So despite only drawing 3mA of current from the Arduino pin, the actual SD card is supplied with > 100mA from the regulator.

I just tested a SD card in an adapter (with level shifters). Without any activity the SD card is only drawing around 0.5 mA. So that is in the capability of an output pin.

Doing a directory list appears to use a maximum of 7 mA, so that is OK.

Writing a file used a maximum of 54.3 mA, which is exceeding the absolute maximum ratings for an output pin (40 mA - recommended only 20 mA for continuous current).

Now you may say that "it works" but the question is: for how long? Exceeding absolute maximum ratings is a path to damaging your processor.

If you want to turn the SD card on and off from time to time, to reduce power, I suggest you arrange to switch the 5V line (and not use a digital output). For example from this page about a low-power temperature sensor I have this schematic:

The MOSFET there switches a 5V line on and off under program control.

That particular design includes a SD card, and that particular gadget has been working for a couple of years now.

Photo of hardware:


Send Arduino data to Database using ESP8266 My project is to receive data from Bluetooth (HC-05) sensor and storing it in the database. I have successfully received data from Bluetooth sensor and stored it in a String variable. Now i have to store this data to the database. I want to use the sensors as standalone (not connecting to the PC - operated on battery). Can I store the data to the database using ESP8266.

Since you mention you operate on a battery (standalone), what exactly do you mean by "the database"? Do you have online connectivity? Do you have any peripherals like an sdcard or other storage?

In case you don't have a permanent online connection, you would need to use some writable memory (like EEPROM) to store your data in some organized form. Since the ESP8266 doesn't seem to have any EEPROM built in, you would need to use its flash memory, like described in those answers.

A database could be as simple as a fixed length string list (essentially how string arrays look in memory). For example if the string data you want to save always has 32 bytes, you could just divide your available storage (e.g. 4096 bytes) to have a "database" wich can store 128 entries (4096/32). Your "database entries" will then be addressable in multiples of 32, you would find the 1st entry at byte 0, the 2nd at byte 32 and so on.

Once you are online, you could send the data out for further processing. Getting the data into a database can be as simple as a https request.


Help needed understanding Due performance I'm going to be writing some performance critical code and have started trying to get an understanding of timers and how much "work" the Due CPU can do per second.  To help get started with this, I wrote a bare sketch that simply increments a counter whilst a timer which ticks every second dumps the value of the counter to the serial log and then resets the counter.  Here's the code I'm using:

#include <Arduino.h>

void EnableTimer7TickEverySecond();

volatile uint32_t gCounter = 0;

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

    EnableTimer7TickEverySecond();

//  while ( true )
//  {
//      ++gCounter;
//  }
}

void loop()
{
    ++gCounter;
}

void EnableTimer7TickEverySecond()
{
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk(ID_TC7);
    TC_Configure(TC2, 1, TC_CMR_WAVE |
        TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1);
    TC_SetRC(TC2, 1, 656000 * 64);
    TC_Start(TC2, 1);
    TC2->TC_CHANNEL[1].TC_IER = TC_IER_CPCS;
    TC2->TC_CHANNEL[1].TC_IDR = ~TC_IER_CPCS;
    NVIC_EnableIRQ(TC7_IRQn);
}

void TC7_Handler()
{
    TC_GetStatus( TC2, 1 );

    Serial.println( (uint32_t)gCounter );

    gCounter = 0;
}

When I run this, I get values averaging 446,000 in the serial log for the increments per second.  That is way lower than I was expecting.  On an ARM chip running at 84MHz, I'd expect at least 14 million increments as few ARM instructions take more than 2 clock cycles and an increment should involve a read from memory, addition and a write back to memory (approx 6 clock cycles by my reckoning).

The timer is configured correctly, the TX led flashes regularly at 1 second intervals as the Serial.println is called.  I've checked for overflow on the counter (oddly, I found that the number of increments when working with a uint64_t was slightly higher).  I've also tried not calling Serial.begin() until I'm about to write the value to the log (and then only writing the value once) and whilst there is a slight increase in "performance", it doesn't account for the whole difference between expectation and reality.

My best guess would be that loop() is called on some sort of timer or has a built in default delay, so it occurred to me that if I comment out the counter increment in loop() and instead comment in the infinite while loop in setup(), I should be able to counteract any delay caused by how frequently the Arduino IDE calls loop().  I have seen other examples that never bother with loop() and just stick all their code in setup().

I do see a performance increase with this setup, but only to around 9 million, not the 14+ million I would expect. Oddly though, sometimes, randomly, the value is 2 or 3 times the "usual" value.  Not between 2 and 3 times, but exactly 2 or 3 times.  This happens regardless of whether I am incrementing the counter inside the loop() function or my own loop inside setup().  It is not a case of the timer "skipping", the output is written every second like clockwork.

So, my questions are:

What does the Arduino library do to make loop() so inefficient?
Is there any harm in keeping all your code inside an infinite loop in
setup() and never returning out of it?
Why would I sometimes see the number of increments being 2 or 3 times
higher than usual?  Could the counter be getting cached (despite
being marked as volatile) and not reset properly?  If so, how can I
prevent this?

What does the Arduino library do to make loop() so inefficient?

Alot.  For a start it's a function, so it has to push registers onto the stack before it runs, and pop them off afterwards.  Secondly there is the "serial event" system outside the loop.  In main.cpp in the core you can see how loop is called:

setup();

for (;;)
{
    loop();
    if (serialEventRun) serialEventRun();
}

  Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?

If you don't use serial events, no harm whatsoever.

  Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?

My guess is the operations you are using are not atomic.  This is, the interrupt is able to be fired right in the middle of doing the series of instructions that perform the increment. The temporary registers end up not being the same as they were at the start of the operation, and consequently the value is corrupted.  You should wrap the increment in a critical section (i.e., disable interrupts before it, and enable them afterwards).

To better analyse the speed of execution you can look at the generated assembly code of your program.  If we look at the disassembled main() function for the bit where it loops you can get this:

80596:  f7ff fe05   bl  801a4 <loop>
8059a:  4b04        ldr r3, [pc, #16]   ; (805ac <main+0x30>)
8059c:  2b00        cmp r3, #0
8059e:  d0fa        beq.n   80596 <main+0x1a>
805a0:  f7ff feec   bl  8037c <_Z14serialEventRunv>
805a4:  e7f7        b.n 80596 <main+0x1a>
805a6:  bf00        nop

loop() consists of this:

801a4:  4b02        ldr r3, [pc, #8]    ; (801b0 <loop+0xc>)
801a6:  681a        ldr r2, [r3, #0]
801a8:  3201        adds    r2, #1
801aa:  601a        str r2, [r3, #0]
801ac:  4770        bx  lr
801ae:  bf00        nop

If we feed that into main() where it calls loop() the finished code looks like:

80596:  f7ff fe05   bl  801a4 <loop>
801a4:  4b02        ldr r3, [pc, #8]    ; (801b0 <loop+0xc>)
801a6:  681a        ldr r2, [r3, #0]
801a8:  3201        adds    r2, #1
801aa:  601a        str r2, [r3, #0]
801ac:  4770        bx  lr
801ae:  bf00        nop
8059a:  4b04        ldr r3, [pc, #16]   ; (805ac <main+0x30>)
8059c:  2b00        cmp r3, #0
8059e:  d0fa        beq.n   80596 <main+0x1a>
805a0:  f7ff feec   bl  8037c <_Z14serialEventRunv>
805a4:  e7f7        b.n 80596 <main+0x1a>
805a6:  bf00        nop

So that is what gets executed for every single iteration of loop().  If we (incorrectly) assume that each instruction takes 1 clock tick, that's 13 ticks.  84,000,000 / 13 = ~6.4 million loops per second.

Now - if we map the instructions against actually how many clock cycles they take, we can get a clearer picture:

bl                  1+P  (P = 1 to 3)
ldr (pc relative)   2
ldr (word)          2
adds                1
str (word)          2
bx                  1+P  (P = 1 to 3)
nop                 1
ldr (pc relative)   2
cmp                 1
beq.n               1 or 1+P (P = 1 to 3)
bl                  1+P (Only if serial event runs)
b.n                 1 or 1+P (P = 1 to 3)
nop                 1

So taking a worst case scenario where P = 3 (pipeline re-fill clock counts, that is), and no serial event running, we can calculate a total number of clock cycles of 4+2+2+1+2+4+1+2+1+4+0+4+1 = 28.

84,000,000 / 28 = 3,000,000 loops per second.

But hang on - that's still much more than you're seeing.  That's because you're still only looking at the small picture.  You're looking at just your sketch and forgetting what else there is going on.

Every millisecond the SysTick_Handler() gets called which does various tasks, including calling the TimeTick_Increment() routine to deal with millis().  That's 1,000 times per second, and that eats into your processing time somewhat.

Another important point is it can't be incrementing while you're running your interrupt.  The more you do in your interrupt (and using serial is a very heavy-weight thing to do in an interrupt) the less of your 1-second slice you get for doing your incrementing.

As an experiment, why not try disabling all the interrupts except just the one you are using for your timer and see how it changes the value.