Piezo not making sound I've used the piezo on other projects with no problem, but for some reason this project isn't working out so hot.

Here's a photo of my current set up.

Here's the basic code that I presumed would make a sound, but no such luck.

void setup() {}

void loop() {
  tone(12,260);
  delay(10);
}

Not sure where to begin debugging this...

As Majenko pointed out, the wires are not connected to the piezo.  By moving the piezo to the correct rails on the other side of the board, the circuit would be completed and the piezo should work.

Edit:
Building on Nick Gammon's comment, the rows of each side of a breadboard are not connected (to allow DIP packages).


How to really shrink a sketch I want to make a sketch that is as small as possible, for test purposes. The problem is, when i compile the BareMinimum sketch (with an empty setup and loop), i get 466 bytes for the Uno and a whopping 4,242 for the Leonardo. Is there any way to write your own code that has no extra functions (namely Timer0 for millis() and delay()). I would also like to be able to disable the keyboard/mouse functions for the Leonardo.

You should be able to create your own board definition with a custom boards.txt file as per https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification. As I see there are several usb features in the leonardo's definition. I would hope that the compiles inclusion of the 4K is based off of these flags and not the processor type.

Where the boards.txt would use the upload, bootloader sections from the Leonardo and the build from the uno.

This is all assuming the core library build does not use processor specific flags to include USB functions.

If you get such working. post back, I am sure others would be interested in such.

I recently ran into this 4K used limitation on a library demo that actually maxed out the UNO and had to put in a

#if !defined(__AVR_ATmega32U4__)
...

around a large chunk of extra features in the sketch to fit on the Leonardo.

I had assume (wrong) that this 4K was because I still included Serial.print which when over the USB's CDC on the Leo. But I see after a memory dump of an empty sketch they are still there.

C:\Users\mflaga\AppData\Local\Temp\build8958339595868119500.tmp>avr-objdump -d sketch_feb13a.cpp.elf > sketch_feb13a.cpp.elf.lst

Which makes sense. As the Leonardo still requires the USB-CDC client (the 4K) as to detect the 1200 Baud connect from AVR-DUDE as to stroke the remote reboot.

Hence making a custom boards.txt without USB in the build, also needs to have

leonardo.upload.use_1200bps_touch=true

removed.

Once loaded on the target, this would require the upload to be synchronized with a manual reset of the target. As the ability to remote reboot is lost.


Combining an NRF24L01 transmitter/receiver with an Adafruit Motor Shield V1? I'm making a vehicle project as a way to learn Arduino. I've set up motor control for a number of DC-motors plus a servo via an Adafruit Motor Shield V1 that I picked up.
Everything works fine, but now I've started looking at adding wireless control for the setup using a second Arduino and two NRF24L01 wireless units. However, reading up on the specs for the NRF24L01 it seems it requires pin 12 on the Arduino, which is already in use by the motor shield.
So, can I combine a NRF24L01 and an Adafruit Motor Shield V1? And if so, how?
If it's not possible, what would be the pros and cons of slaving the shielded Arduino to a Nano that would carry the NRF24L01, versus replacing the Adafruit motor shield with external DC motor driver(s)?
Edit:
I now found this previous question:
Motor shield and wireless transceiver compete for same pins
A difference in my project is that I'm not using stepper motors, so perhaps that makes a difference?

One of the problems of the Uno is that the hardware SPI pins conflict with some of the PWM pins. If you want lots of motor control then you have it at the expense of no SPI. If you want SPI then you have it at the cost of reduced motor control.
The V1 shield uses a shift register for some of the motor signals, and that has to fit its signals in around the available PWM pins, so that as well has spilled over into the SPI pins (since you can't use SPI because of the PWM pins that really doesn't matter).
So no SPI means no nRF24L01.  Or does it?
You could (though I don't know of any libraries that handle this) use "bit-banged" software SPI on other pins (such as the analog pins) to communicate with the nRF24L01. Your mileage may vary with that, but it is technically possible - as long as you can find (or write) the right software support for it.
Would it be better to throw more hardware at it and have the wireless connection on a dedicated MCU? I would say, yes. Not only does it mean you can use existing libraries to communicate with the nRF24L01 without any worries of conflicting pins, but you get to compartmentalise your software into discrete units that don't interfere with each other. Parallel processing :)
How to communicate between the two? Well, you have I2C available on the analog pins A4/A5, which is well documented and plenty of examples. Or you could use serial, although the 328P's lack of serial ports means that you'd probably be working with SoftwareSerial which is ropy at best.  I'd pick I2C out of those two TBH.


Connect multiple pins to same VCC using breadboard Ok so I am pretty green as far as AVR programming is concerned so bear with me.

I am doing a project with an ATmega32 MCU on a dev board which has 4 VCC pins.
The project includes a GPS, SD card and a TFT display. Currently, the GPS and SD card take up 2 out of the 4 VCC pins for powering themselves up. I have two free left.

The display controller I have is the SSD1289:

I've connected it to my MCU, the VCC pin on the display took up one more VCC pin so I have one VCC left.
I've been reading up and I've found that the LED_A and RD pins need to be connected to 3.3V, that is VCC.
The LED_A pin should also have a resistor on the line connecting it to VCC.

First question - can someone confirm this is the way to connect it?

Second question - Is it possible to, for example, connect the VCC and RD pins of the display to the same VCC using a breadboard? So then I have one VCC left to connect to LED_A pin through a resistor? I don't know if multiple pins can share the same VCC. Will the voltage drop if I connect two pins to it?
Is this safe to do?

You have basic misconceptions there:

Vcc is the power input (!) for the Atmega, not an output to provide current to other parts. Your power supply (whatever you use as one) should be connected to every Vcc pin at the same time. Sure, the Vcc pins are internally connected, but the Atmega has multiple of them, so that the needed current does not have to flow through a single pin. Also you don't want to draw the current for peripherals through the Atmega chip itself (which would happen, when you connect the power source to one of them and the peripherals to another). So every device in your circuit, including the Atmega, has it's own Vcc pin, which needs to be connected directly to the power supply. That is ok and correct, as long as the power supply can provide enough current for all components. If it doesn't, you need to buy a power supply, that can.
When connecting device to one pin, the number of devices is not imporant. The current draw is what is important. For example let's take simple digital output pin of the Atmega. It can provide up to 20mA (recommended value; max. 40mA for a short time). We must no exceed that value. So we can connect 1 device, that draws 20mA, or 2 devices, that draw 10mA each. Or 100 devices, which draw 0.2mA each. The number is not important, only the total power draw. The current will drop, when you draw more current, that the source can provide. In that case often the source will be damaged or at least go into thermal emergency shutdown (as for the voltage regulator of a genuine Arduino).

So the Todo for you: Connect every Vcc pin, that you have, directly with the power source.


433MHz sending not receiving I'm trying to send data using these cheap parts.
When I check the voltage on the data port of the transmitter, I see what I expect, 1.2 and 0.6 fluctuating while sending.
But when I check the receiver I get 0. I've got 3 of the sets and tried them all. Also tried it with running the transmitter on 11V for some extra power. I've added a LED to the transmitter to see when it transmits and I've added a not-so-good antenna to both while they are only 5cm apart during my tests.

Any advice would be appreciated.

Receiver
FS1000A with a LR433A

#include <VirtualWire.h>

const int led_pin = 6;
//const int transmit_pin = 12;
const int receive_pin = 11;
//const int transmit_en_pin = 3;

void setup()
{
    delay(1000);
    Serial.begin(9600);  // Debugging only
    Serial.println("setup");

    // Initialise the IO and ISR
    //vw_set_tx_pin(transmit_pin);
    vw_set_rx_pin(receive_pin);
    //vw_set_ptt_pin(transmit_en_pin);
    //vw_set_ptt_inverted(true); // Required for DR3100
    vw_setup(1000);  // Bits per sec

    vw_rx_start();       // Start the receiver PLL running
}

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

    if (vw_get_message(buf, &buflen)) // Non-blocking
    {
  int i;

        digitalWrite(led_pin, HIGH); // Flash a light to show received good message
  // Message with a good checksum received, print it.
  Serial.print("Got: ");

  for (i = 0; i < buflen; i++)
  {
      Serial.print(buf[i], HEX);
      Serial.print(' ');
  }
  Serial.println();
        digitalWrite(led_pin, LOW);
    }
}

Transmitter

#include <VirtualWire.h>

const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;

void setup()
{
  // Initialise the IO and ISR
  vw_set_tx_pin(transmit_pin);
  vw_set_rx_pin(receive_pin);
  vw_set_ptt_pin(transmit_en_pin);
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(1000);   // Bits per sec
}

byte count = 1;

void loop()
{
  char msg[7] = {'h','e','l','l','o',' ','#'};
  Serial.println("sending");
  msg[6] = count;
  digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  digitalWrite(led_pin, LOW);
  delay(1000);
  count = count + 1;
}

If you are not getting anything on the receiver, then the receiver is definitely the problem. These units will boost the gain until it get some signal, any signal.

You should be able to power the receiver + and GND (I have one, which ran on 5v, I can't see if these are the same), and put a multimeter from GND to Data, and you should get about half of Vcc, probably fluctuating a bit. If you look at the same with an oscilloscope, it should fluctuating wildly between 0 and Vcc volts. All of this should work without a transmitter, and without an Arduino (you will need a power supply for the receiver).

Note: this is from memory, I don't have mine here to test.

Once you are getting "random data" (background noise), you can progress to sending a signal.

Note that you should keep your "1"s and "0"s balanced to get a clear signal - check out Manchester encoding (this encodes a "1" as "1,0", and a 0 as "0,1", so there will be a perfect balance). You might also want to send a 1010101010 at the start - this gives the receiver a chance to adjust the gain to the correct level. Or, you can use some width-based encoding (e.g. "slow 1, slow 0" for a "1", and "fast 0, fast 1" for a "0").


How to specify a timer's name depending on the chip it will be compiled to? I need to enable a timer interrupt for a chip, and in the mean time, I am testing the code on Arduino Nano rather than (feed the chip, test the chip)++.
So as part of the code I have to TIMSK0 |= (1 << OCIE0A); which works great on the Arduino Nano, but has to be changed to TIMSK (without the 0) for the ATtiny45.
I was planning to go for something along the line of
#define NANO//Put // in front for the AtTiny45
#ifdef NANO
  const char in  = A0;
  const char out = 3;
  const char pwr = 10;
  char *timer = &TIMSK0;
#else
  const char in  = 3;
  const char out = 0;
  const char pwr = 1;
  char *timer = &TIMSK;
#endif
//...
*timer  |= (1 << OCIE0A);

So here are my three questions:

Do #these commands take space on a chip?
Is a pointer the way to go for this kind of things?
Am, am I doing it right?

Just as a complement to Delta_G's answer:

The names TIMSK0, OCIE0A, etc. are already preprocessor macros
so, for consistency, it makes sense to define your own preprocessor
macros for them. I tend to be lazy and use one of the already defined
names, like
#ifdef TIMSK0  // support both ATtiny{25,45,85} and ATmega328P
# define TIMSK TIMSK0
#endif

A const pointer for &TIMSK0 is fine though.

The macros identifying the MCU are defined to the value 1. Thus you
have the choice between these three idioms:
#ifdef __AVR_ATtiny45__
...
#endif

#if defined(__AVR_ATtiny45__)
...
#endif

#if __AVR_ATtiny45__
...
#endif

The third one is convenient when you want to address several MCU
models with the same code:
#if __AVR_ATtiny25__ || __AVR_ATtiny45__ || __AVR_ATtiny85__
...
#endif


How to program micro chips directly with USB Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?
Where can i find information on the protocols/standards to do such a thing?

More specifically, I want to be able to make a custom pcb for my Attiny85 chips with a usb connector. I would prefer not to use the arduino IDE.
Is it possible to program this chip like so?

Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

The bare chip? Generally, no.

Some chips that include USB hardware also may include a DFU bootloader in ROM. If your chosen chip has this, then yes you can - you just need to wire it up and use a suitable DFU firmware upload program to install your compiled code into the chip.

However chips that don't have USB will never have a USB DFU bootloader in them. In such cases is is your responsibility to create (or otherwise obtain) a suitable bootloader that you will install into the chip.

Digispark and Adafruit both do that.  They take a chip that doesn't have USB and install software that tries to (poorly) emulate USB over GPIO pins1.

For chips that do not have actual USB hardware in them it is far more common to use a UART-based bootloader - simply because this is a much lighter and more "correct" way of doing it.

If you want to use a direct USB connection for your device you should be selecting a chip that has USB built into it (AVR "U" series2, most PIC32, many ARM-based chips) which will allow you to have proper USB communication instead of slow HID and custom (non-standard) protocols only3.

Note that at no point does your choice of bootloader, or method of communication with the bootloader, tie you in to using the Arduino IDE.  The IDE just compiles the code then runs an external program that communicates with the bootloader (different bootloaders need different programs to communicate with them). How you compile the software is up to you. How you execute the bootloader upload program is up to you.

Personally I think that's a horrible idea and should NEVER be done. I'm a purist though.
Such as the ATMega32U4 used on the Leonardo and Micro boards.
VUSB can only (barely) run fast enough for USB 1.1. That means only HID protocols are officially supported (keyboard and mouse), and anything else is non-standard and requires special supporting software to work with it.


Is there a practical way to broadcast and receive ascii payloads over ethernet or wifi? How best might arduino nodes pass incoming serial ascii messages out as ascii network broadcasts for all others to receive and pass out through their serial ports?

ie: typing a msg from the IDE serial monitor of any ethernet node should cause that msg to be output to the serial monitors of all other nodes.

The magical trick you are looking for is Ethernet UDP Broadcast. By chance there is an example sketch in the Arduino Tutorial. I cannot say if it is up to date but this will help you get started.

Cheers!


I want to stream audio from an Arduino to a device on the wifi I only started learning Arduino recently. This is my first project.
So the idea for the project is that there will be an Arduino board(Ideally an Uno but I don't know if another board would be better) and when you hold a button down it will transmit what you are saying to a device on the wifi. I know I will have to get a WiFi module and like a microphone and button, so can you help me figure out just the gist of how the project will go and what parts I should get.
Thanks!

An Arduino can do this, but this is a very advanced problem on an Arduino. It sounds like perhaps you need something more plug-and-play. In that case, buy a Raspberry Pi 4 starter kit and a USB microphone, and start working on the problem from there. The Raspberry Pi 4 is a Linux computer, so everything you do will be writing scripts or programs (in any language: it's just a regular computer, so use Python, C, C++, Java, bash, whatever you want) to run on its Raspberry Pi OS (formerly called Raspbian) Linux operating system.
If you go this route, you'll want to ask your questions on the Raspberry Pi Stack Exchange as well.
Keep in mind the question you asked is too broad. You are generally expected to do your own background research and then ask more specific questions, demonstrating what you've already tried.
Getting an Arduino to send out microphone data is, like I said, a very advanced subject and project (think: professional level / expert hobby level) unless you can Google and find pre-made libraries and how-tos on the subject.
Essentially, for the Arduino Uno route you'd need to do some fancy high-rate ADC sampling with a modified ADC clock rate in a special ADC mode which takes repeated samples and then interrupts your code when a sample is ready, rather than just doing normal analogRead() since that is both blocking/polling-based which wastes clock cycles and creates sample jitter which causes audio distortion, and then you'd need to send this data via some Wifi shield (add-on board) or an ESP8266 or something, or via some other technology (wired or wireless) to a computer to pass it on to the internet. This may involve binary packetization/bit-packing, error checking, buffering, etc., all of which is its own special skill to acquire.
Some of my projects have taken me 3+ years to complete them, since I began complicated projects as a beginner. This is one of those multi-year type projects for a beginner for sure.
(Heck, if you give me two LEDs and two resistors and an Arduino Nano, with those items alone, I can send you on your way to work 8 hrs a day for 3 months straight on projects. It's easy to under-estimate the complexity of something until you're neck-deep in it.)
Update: if you want to go the Arduino route, here's some tips to get you on a search route more likely to get you to a solution faster. Again, no doubt an Arduino Uno can do this. It for sure can. But, a faster Arduino can do it easier and better. So:

Google search for projects on Adafruit which may do this. Ex: Google search for "adafruit stream audio". Their tutorials are 2nd to none--the best in the world--and their products top-notch.
Search for projects on Sparkfun which may do this. Ex: Google search for "sparkfun stream audio". They also are excellent and have world-class tutorials.
Search for projects which do this with a Teensy, Zero, Due, or other high-speed 32-bit microcontroller, instead of an Uno. Audio processing is more difficult for a slower 8-bit Uno than for any of those 3 Arduino/Arduino-compatible devices.
Also look on Instructables.com for tutorials and help.
One more thought: Google search for "atmega328 stream audio to wifi" (an Uno uses the ATmega328 microcontroller, so that's a good search term to use)

Update: also take a look at this tutorial by GreatScott (who is also super awesome) (https://www.instructables.com/id/Make-Your-Own-Spy-Bug-Arduino-Voice-Recorder/), which uses this AVR-based (for ATmega328: Arduino Uno, Nano, Pro Mini, etc., or ATmega2560: Mega) advanced audio library for both recording and playing back audio. See:

https://github.com/TMRh20/TMRpcm

Recording Audio
Audio streaming over NRF24L01+ radio link


Can I connect esp32 to a phone USB charger? I have a USB charger. Is it ok to connect it as a power supply for esp32?

Edit: i have a dev board esp32

In principle yes (see also comment in update).

The voltage is ok (5V), typically USB, and it doesn't differ from the output of a computer USB port.

The output current is max 2000 mA, so check if your project (ESP + related hardware powered by this USB), is not exceeding 2000 mA. The ESP needs much less than 2000 mA, so if you didn't have a lot of external components or motors than you will be safe.

Update

Important omment from Sim Sson: The bare esp32 is not 5V-tolerant, so using a usb-charger is only ok for esp modules that have a voltage regulator onboard.


Input 4-digit number using 4*4 keypad and show in serial monitor #include <Keypad.h>

int myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input
  for (int i = 0; i < 4;){
    if(keypad.getKey()!= NO_KEY) {
      myNum[i] = keypad.getKey();
      i = i+1;
    }
  }
  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}

I want that when I press a 4-digit number on the keypad it should be shown in the serial monitor. This code gives 0000 when I press any key on keypad.

keypad.getKey() is non-blocking as you can read here: it will return a value immediately, even if no key is pressed.  You have a for loop which will increment i each time, and you also increment it yourself. So what's happening is that your code is immediately making four readings, all of which are no-key-pressed so it doesn't store them, and then printing whatever happens to be in the myNum buffer.

Instead, you need to wait each time until a key is pressed, and only then move to the next digit. There are of course many ways you could do this.  I hope this is clear:

#include <Keypad.h>

int myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input

  for (int i = 0; i < 4; ++i){
    while((myNum[i] = keypad.getKey())==NO_KEY) {
      delay(1); // Just wait for a key
    }
    // Wait for the key to be released
    while(keypad.getKey() != NO_KEY) {
      delay(1);
    }

  }

  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}


Clock generator up to 8 MHz using pin 3 arduino nano I would like to generate square signal up to 8 MHz using internal timer of arduino, I have done successfully in pin 11, but i want to change it in pin 3, but still stuck. Here is the code

 pinMode(11,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2A0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2A = 1;

from this page here
How can i change the pin to pin 3?

Thank you

The MCU Timer Outputs are hardwired to specific pins. Arduino Nano (ATmega328p) pin 3 is the MCU pin PD3 and may be connected to Timer 2 output logic, OC2B with Output Compare Register 2B (OCR2B). Waveform Generator Mode and Timer Clock prescale are the same as above.

 pinMode(3,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2B0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2B = 1;

Cheers!


Arduino uno, 2x parallax continous servos (BOE), wifi shield power draw I am unable to properly connect those things together with batteries:

Arduino Uno
Parallax continuous servo
Arduino wifi shield

5xAA batteries are connected through power jack to arduino which I assumed would power both arduino and the wifi shield and then I have 1 9 volt battery to power 2 servo motors.

With this setup it seems like I can only get to run 1 servo at a time.

Here is a picture how it looks like: http://imgur.com/0jtbPHT

I'm really desperate for any advice/guidance when it comes to powering this thing.

9V batteries can only supply  very little current. So two servo's is too much.

Just use another set of multiple AA batteries for the servo's.


Build error on a phantom file that is not in my sketch, but somehow created in AppData/Local/Temp\build on attempt to build  I get the following error

C:\Users\gmyer\AppData\Local\Temp\build5d24776aeb7b2efec3566cec737c36d8.tmp\sketch\trash\bootloader.c:1:1: error: unknown type name 'This'

 This modules tests receiving vacuum data from the

 ^

The problem is that I have no file of that name, and no text that exactly matches that any where in my sketch.  and my sketch is located in C:\Software

I have tried rebooting, deleting the Temp directory, reverting to known working code.  but it keeps regenerating.

I found the offending file in a sub directory of the C:\Software sketch directory.  I had a subdirectory called trash, and the Arduino build found it from there, and put it in AppData then referenced the error from there.


Linux SSH command for Arduino Console I have a Leonardo with a Yun shield, and I would like to be able to control the arduino with a windows form app, but thats besides the point for now at least. Currently, I am using putty and the commands Telnet Localhost 6571. However, I would like to avoid doing that and I was wondering if anybody new how to communicate with the arduino from port 22 at the yun's IP, rather than connecting to the yun and then to the remote local machine. That or I am missing something entirely!

This is the code I am using to try and access the console port of the Leonardo:

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            //connect to arduino
            ConnectionInfo ConnNfo = new ConnectionInfo("10.1.1.211", 22, "root", new AuthenticationMethod[] { new PasswordAuthenticationMethod("root", "123456789") });
            using (var sshclient = new SshClient(ConnNfo))
            {
                sshclient.Connect();
                //connect to console port of arduino
                TcpClient tcp = new TcpClient("localhost", 5671);
                sshclient.Disconnect();
            }
            Console.ReadKey();
        }
    }
}

Thank you

The console port is only listening on 127.0.0.1 (for security), so only the Yun itself can connect to the console.

You can weaken security and open the port up to the entire local network by editing the file /usr/lib/python2.7/bridge/console.py and change the value 127.0.0.1 to 0.0.0.0.

Any machine on your local network will then be able to connect directly to port 6571.


Arduino Mega failure after first use of Mega Shield power connector I have an XDRduino Mega clone with ATmega2560 and ATmega16U2 USB support chip.  I also have a Sensor Shield (same vendor), which provides screw terminals to Vin and Ground.

I connected the board with USB, loaded "Blink", and then changed the time interval.  Next I connected a 20x4 LCD using the Sensor Shield and a breadboard and loaded LCD "Hello world".  All seemed fine with the new board.

Each time I powered on or reset the Mega, the TX and RX LEDs flashed a couple of times and then my sketch started running.

Then I disconnected it from the PC (no USB for power anymore) and connected a (working from another project) S-60-12 power supply, DC Output 12V 5A to the shield screw terminals.  I verified polarity -V to GND, +V to VCC.

OK, I swear I hooked it up correctly.  But if you tell me that hooking it up backwards would explain all the symptoms below, then yes I'll believe you that I screwed up {sob}.

(And yes, you're right, there is no diode protection on Vin, just on the dc power jack.  Dummy me.  Double dummy me, as there was a screw type power plug laying unused on the bench {groan}.)

About 4 seconds later, I heard a snap and immediately pulled the plug on the power supply.  Yes, something probably smoked, but let's refine at bit, please.

I moved the Mega to my PC, (disconnecting the external power supply so to use only USB for power).  It is no longer recognized as a USB device, and the Arduino IDE (1.6.5) no longer finds the USB serial port.

Voltages at 3.3V pin and 5V pin are correct.  I've also probed the regulator and comparator and all looks well for the power circuitry. F1 is not blown (or there would be no power as USB is the only source).

Item: The TX and RX leads are on solid.  I expected them to flash then turn off.  (Power LED is on solid, which is normal.)

Item: The reset pin for the Mega reads 1.41 V.  It's connected through a 10K pullup to +5 V (reads 4.63 at USB pin, 4.53 at the 5V pin).  This seems way too low.

Item: The reset pin for the 16U2 reads V+ (4.35) and is has a 10K pull-up.

Item: AREF is 50 mV.  I believe it should be 1.1 V or 2.56 V.

Question: Is it reasonable to think the 2560 may be dead, and the LEDs are on because the 16U2 can't talk to it?  Any way to test this theory?

(If the 16U2 were bad, it would still be possible to program the 2560 via the ICSP header, thus salvaging something...)

Question: The 16U2 won't do the USB connection dance with the PC because the 2560 is dead?  Should the 16U2 to try to connect no matter what the state of the 2560?.

Question:  If the 16U2 is dead, should TX and RX LEDs be lit?

Question:  If I had reversed the hookup, should not the regulator (P1117 chip) have saved me?

Question:  Has anyone else had a failing component (other than the 2560 & 16U2) with these symptoms?

I want to make this obvious to the casual reader:  Mega Sensor Shields -- all versions I've data on -- run the power connector to +5V.

The power connector is not power in, as defined by the base board.  In fact, there is no direct way to get to the base board regulator from the shield.  (A pin exists for Vin, but it isn't connected to anything on the shield.  It's mechanical support.)

It's intended to supply more current to devices connected via the shield than the base board does.

There is a jumper that disconnects the sensor shield +5 rail from base board power to allow independent +5 volts distribution to the shield attached devices.


Arduino MKR1000 and DHT11 not giving correct output for temperature and humidity I've been trying to follow this tutorial to wire my Arduino MKR1000 to a DHT11 temperature and humidity sensor, but my output consists of either 0's or 255's for both values. I've tried several different arrangements of wires, but none seem to work. Here's my current setup:

And here's my code:

// Example testing sketch for various DHT humidity/temperature sensors // Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN A0     // what digital pin we're connected to; MAY BE PROBLEM

// Uncomment whatever type you're using!
#define DHTTYPE DHT11
//#define DHTTYPE DHT22
//#define DHTTYPE DHT21

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs. DHT dht(DHTPIN, DHTTYPE);

void setup() {
    Serial.begin(9600);
    Serial.println("DHTxx test!");

    dht.begin();
}

void loop() {
    // Wait a few seconds between measurements.
    delay(2000);

    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    float h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    float t = dht.readTemperature();
    // Read temperature as Fahrenheit (isFahrenheit = true)
    float f = dht.readTemperature(true);

    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
    }

    // Compute heat index in Fahrenheit (the default)
    float hif = dht.computeHeatIndex(f, h);
    // Compute heat index in Celsius (isFahreheit = false)
    float hic = dht.computeHeatIndex(t, h, false);

    Serial.print("Humidity: ");   Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.print(f);
    Serial.print(" *F\t");
    Serial.print("Heat index: ");
    Serial.print(hic);
    Serial.print(" *C ");
    Serial.print(hif);
    Serial.println(" *F");
}

And here's the diagram of an Arduino MKR1000:

This is my first time using a micro controller, so any help is much appreciated.

UPDATE: Here's my setup with 2 10k resistors in parallel added:

I have the identical sensor so I've got two suggestions for you.

I don't see the 5k ohm pull-up resistor on either of the pictures you've uploaded. You could try adding it first and see if that solves the problem.

There are several versions of the DHT11 library for Arduino out there. This is the one that worked for me: https://github.com/adidax/dht11. Have a look at this answer for a sample sketch: Arduino Uno Sensor DHT11 Failed to read from DHT sensor.

EDIT: Connect the sensor data line to digital pin 3 on your Arduino MKR1000.

// 5k ohm pull up resistor is used on the data line.
// Sensor operates at 5VDC.
// Data line connects to Arduino Uno pin 3.

#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 3

// Sensor calibration. Start with 0 for each.
const int HumidityCorrection = -10;          // -10 worked with my sensor.
const int CelsiusTemperatureCorrection = 2;  // 2 worked with my sensor.

const float FahrenheitTemperatureCorrection = CelsiusTemperatureCorrection * 1.8;

// Update the serial display every 60 seconds.
const float UpdateSerialDisplay = 60000;

// Celsius to Fahrenheit conversion.
double Fahrenheit(double celsius){
  return 1.8 * celsius + 32;
}

void setup(){
  Serial.begin(9600);
  // Minimum wait for good data recommended is 1 second.
  delay(2000);
  Serial.println("DHT11 TEST PROGRAM ");
  Serial.print("LIBRARY VERSION: ");
  Serial.println(DHT11LIB_VERSION);
}

void loop(){
  Serial.println("");
  int chk = DHT11.read(DHT11PIN);
  switch(chk){
    case DHTLIB_OK:
      //Serial.println("OK");
      break;
    case DHTLIB_ERROR_CHECKSUM:
      Serial.println("Read sensor: Checksum error");
      break;
    case DHTLIB_ERROR_TIMEOUT:
      Serial.println("Read sensor: Time out error");
      break;
    default:
      Serial.println("Read sensor: Unknown error");
      break;
  }

  Serial.print("Humidity: ");
  Serial.print("\t");
  Serial.print(DHT11.humidity + HumidityCorrection);
  Serial.println(" %");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(DHT11.temperature + CelsiusTemperatureCorrection);
  Serial.println(" C");

  Serial.print("Temperature: ");
  Serial.print("\t");
  Serial.print(round(Fahrenheit(DHT11.temperature) + FahrenheitTemperatureCorrection));
  Serial.println(" F");

  delay(UpdateSerialDisplay);
}


PWM multiplexing on Arduino nano simulate this circuit – Schematic created using CircuitLab

Its a simple project. I am trying to drive 3 RGB LEDs using Arduino Nano. Since Arduino Nano does not have 9 PWM pins, the only solution I can think of by multiplexing them. I have try multiplexing 12 7-segments driven by atmega16, the results was satisfying. Is it possible to do PWM multiplexing on Arduino Nano?
So far, here is what I have done:

const int R=9, G=10, B=11, M1=5, M2=6, M3=7;

//I use pin 5,6,7 as selector since they are on same PORT (PORTD)

void setup()
{
    pinMode (R,OUTPUT);
    pinMode (G,OUTPUT);
    pinMode (B,OUTPUT);

    pinMode (M1,OUTPUT);
    pinMode (M2,OUTPUT);
    pinMode (M3,OUTPUT);
}

void led(int r, int g, int b)
{
    analogWrite(R,255-r);
    analogWrite(G,255-g);
    analogWrite(B,255-b);
}

void loop()
{
    for(int i=0; i<256; i++)
    {
        led(0,0,i);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B10000000;      //select LED-1

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

        led(i,0,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B00100000;      //select LED-3
    }

    for(int i=256; i>0; i--)
    {
        led(0,0,i);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B10000000;      //select LED-1

        led(0,i,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B01000000;      //select LED-2

        led(i,0,0);
        __asm__("nop\n\t");     //one clock cycle delay
        PORTD = B00100000;      //select LED-3
    }

}

But still, this does not work. The result is all the led turned on, with 'a little bit' different color, mainly white with a little addition of another color (while it supposed to be contrast, R, G and B for each LED), and its blinking. The blink is very short, but still, its annoying. One possibility I can think of my code still not optimum.
Someone had an idea?

EDIT
I fixed the diagram, I hope the diagram does not make any misunderstandings. As the suggestion from @jwpat7, I forget to inform that the led still error even if there is just one for-loop.
I am using __asm__("nop\n\t") as delay substitution because "theoretically", 1 clock cycle from 16mHz clock is shorter than 1 microseconds. (correct me if I am wrong, but I think its about 62.5 ns)

Thanks in advance

I've copied and slightly modified your diagram, as below.  Note the added connections of R1, R3 cathodes to that of R2, and similarly for green and blue LEDs.

simulate this circuit – Schematic created using CircuitLab

I'm supposing that unlike the original diagram, this one represents what you actually wired up.

A basic problem with your program is that it spends most of its time changing PWM settings, without letting PWM cycles actually occur.  To see this, do some timing analysis on the code.

The code repeatedly executes sections of code like the following:

    led(0,i,0);
    __asm__("nop\n\t");     //one clock cycle delay
    PORTD = B01000000;      //select LED-2

The call to led() results in three calls to analogWrite().  As seen by perusing at garretlab the source code for analogWrite(), digitalWrite(), and pinMode(), each of those analogWrite() calls takes a few handfuls of cycles – let's say 50 at most – so the three lines of code shown above take less than a dozen microseconds to execute.  Thus each of the two for loops takes less than 10 milliseconds to complete, causing the loop() routine to run more than 50 times per second.  Persistence of vision will result in observers just seeing the average level of light, rather than any ramping up or down.

To fix the ramps-not-visible problem, determine how long you want each ramp up or down to take, and add corresponding delays in the for loops.  For example, suppose you want to go up in one second and down in two.  As 1000000 μs /256 passes ≈ 3906 μs per pass, you could add delayMicroseconds(3906-36) at the end of the first for loop, and delayMicroseconds(2*3906-36) at the end of the other, to achieve the specified rates.  (The -36 term accounts for time used by other code in each loop.  It's probably an overestimate and perhaps should be left out.)

However, the previous paragraph doesn't take multiplexing effects into account.  You may, of course, want a different PWM level for each of the nine different LED chips.  It probably is practical to just directly use as many PWM outputs as you have available, and emulate PWM in software for any remaining LEDs.

For more information about software PWM, see some articles that google turns up, including:
• Arduino PWM pin vs digital pin PWM simulation on electronics.stackexchange, which presents basic ideas and some pros and cons of software-based PWM
• AnyPWM Revisited, a blog article by Nick Borko about PWMing 12 LEDs using software PWM
• PWMAllPins, an arduino.cc article apparently by Paul Badger or Seth Wolf about PWMing 11 LEDs using software PWM

Generally, software PWM hogs computing cycles and can be difficult to coordinate with other calculations.  But if PWM control is the only significant task a processor is handling, software PWM can be an economical way to produce extra PWM pins.


DS18B20 - Thermometer and Sensor discrepancy (varying) This is a follow-up question from this other question

I followed of the user Jot (get the sensor away from the sun and use a delay in arduino program)

But the results are still varying.

I recorded the temperature measured in the sensor, the temperature measured using a mercury thermometer and calculated the difference. The data was collected within 8 days

Here's the data (sorted):

SENSOR  THERM   DIFF
32.69   31.25   1.44
32.00   30.25   1.75
31.94   30.50   1.44
31.87   30.50   1.37
31.44   29.50   1.94
31.00   29.00   2.00
30.75   29.00   1.75
30.50   29.00   1.50
30.44   28.80   1.64
30.31   28.90   1.41
30.25   28.75   1.50
29.87   28.00   1.87
29.81   28.00   1.81
29.81   28.00   1.81
29.81   28.25   1.56
29.75   28.20   1.55
29.69   28.00   1.69
29.56   27.00   2.56
28.75   27.25   1.50
28.69   27.00   1.69
28.56   27.00   1.56
28.44   27.00   1.44
28.25   26.80   1.45
28.00   26.50   1.50
28.00   25.50   2.50
28.00   25.00   3.00
27.75   25.50   2.25

The average difference is around +1.76°C but that's not linear, and as you can see there are fluctuation in the same sensor value, 28.00 has three associated temperatures(25.0, 25.5, 26.5).

I'm not sure what to do, if the difference was regular I could simply subtract that from the sensor readings, but it seems that it varies a lot(Min: 1.37°C, Max: 3.00°C)

Any ideas?

Can you buy a few more from other (more reliable) sellers ? Perhaps it is damaged. Did you accidently connect it wrong and it got very hot ?

There has been counterfeit DS18B20 sensors, but they were transistors that were re-labeled as DS18B20. Those didn't work at all.

You have not convinced me that you are only measuring the air temperature. Maybe there is still something nearby that causes it to get warmer. The 3 degrees difference is a lot. There must be a good reason for that, or else the DS18B20 is broken. How accurate is that mercury thermometer ?

I wrote before: "To be sure you can put it in distilled water at sea level at 0°C (water and ice cubes) and 100°C (boiling water)". That is what I did, out of curiosity. It turned out to be accurate.


character input for an integer variable? Im trying out the code found here , let me quote the section of code that bothers me.

// set pin numbers for switch, joystick axes, and LED:
const int switchPin = 2;      // switch to turn on and off mouse control
const int mouseButton = 3;    // input pin for the mouse pushButton
const int xAxis = A0;         // joystick X axis
const int yAxis = A1;         // joystick Y axis
const int ledPin = 5;         // Mouse control LED

xAxis is a variable that is defined as an integer , however, it is being assigned a character(A0), How is this possible? I tried to compile and run the code and everything works well. I'm quite surprised!

A0 and A1 are not characters or what you mean probably: strings.
Because it would be written as "A0" and "A1".
The types of A0 and A1 are probably integers or another numeric type.

However, these are probably defined as (constant) integers, e.g.:

const int A0 = 100;
const int A1 = 101;

(note 100 and 101 are random numbers)

or defined by a macro. e.g.:

#define A0  100
#define A1  101

So the variables A0 and A1 are actually integers (or assigned as numeric values by a define).


Cannot run WiFi sketch on ESP-01 I can upload simple sketch on my ESP-01 like:

void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

I also ran successfully the sample ESPWebServer -> HelloServer

But if just modify my sketch to include #include <ESP8266WiFi.h>

#include <ESP8266WiFi.h>

void setup() {
  Serial.begin(115200);
  Serial.println("Hello there");
}
void loop() {
  Serial.println("Hello from loop");
  delay(1000);
}

I got this result in the serial monitor:

  ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
vbb28d4a3
~ld

My ESP-01 is connected to my computer through FT232RL FTDI with the following cabling:

FTDI GND - GND
ESP TX - FTDI RX
ESP RX - FTDI TX
ESP VCC - VCC 3.3V
ESP GND - GND
ESP CH_PD - VCC
ESP GPIO2 - VCC
ESP GPI00 - GND to upload sketch, VCC to run sketch

Here is a picture of my cabling (the USB of both the TTL and power supply MB102 are connected to my laptop):

Also, regularly my sketch fails to load correctly:

-Sometimes it does not load at all and I get this after compilation before uploading starts:

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

- Sometimes it fails at the end of the upload:

Uploading 256064 bytes from C:\Users\20000263\AppData\Local\Temp\arduino_build_32221/ESP01-Basic.ino.bin to flash at 0x00000000
................................................................................ [ 31% ]
................................................................................ [ 63% ]
................................................................................ [ 95% ]
..........warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_DATA) failed
warning: espcomm_send_command: wrong direction/command: 0x01 0x03, expected 0x01 0x04
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Any idea about what is wrong ?

FTDI adapters often don't provide enough current to run the power-hungry wifi features of the ESP8266. So as soon as you fire up wifi, you brownout the chip and cause it to reset.

Use a battery, a dedicated ESP8266 flasher, a 3.3v LDO, or something besides the on-board 3.3v connection the USB-Serial adapter provides.


Arduino Servo circuit by example I have an Arduino program that uses the Thread library to create two concurrent threads, where:

Thread #1 blinks an LED every 500ms; and
Thread #2 blinks another LED every 250ms

I wired things up, flashed the program to my Arduino Due, and it ran beautifully.

I am now trying to add a 3rd thread that sweeps a servo back and forth.

Here's my design:

And the schematic that Fritzing generated for me:

And an accompanying actual picture of the wire up:

If you can see it, I've rigged Pin 10 as an OUTPUT, and attached the servo's signal line to Pin 9. Here's the code:

#include <Thread.h>
#include <ThreadController.h>
#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;
int SERVO_PWR_PIN = 10;
int LED_1_PIN = 12;
int LED_2_PIN = 13;

Servo servo;
int pos = 0;

static bool LED_1_STATUS = false;
static bool LED_2_STATUS = false;

Thread blinkLED1Thread = Thread();
Thread blinkLED2Thread = Thread();
Thread servoThread = Thread();
ThreadController master = ThreadController();

void setup() {
    pinMode(LED_1_PIN, OUTPUT);
    pinMode(LED_2_PIN, OUTPUT);
    pinMode(SERVO_PWR_PIN, OUTPUT);

    servo.attach(SERVO_SIGNAL_PIN);

    blinkLED1Thread.onRun(blinkLED1);
    blinkLED1Thread.setInterval(250);

    blinkLED2Thread.onRun(blinkLED2);
    blinkLED2Thread.setInterval(500);

    servoThread.onRun(runServo);

    master.add(&blinkLED1Thread);
    master.add(&blinkLED2Thread);
    master.add(&servoThread);
}

void loop() {
    master.run();
}

void runServo() {
    // Give the servo a few seconds to reset to the starting position.
    servo.write(0);
    delay(5000);

    while(true) {
        for(pos = 0; pos < 180; pos += 1)  {
            servo.write(pos);
            delay(15);
        }

        for(pos = 180; pos >=1; pos-=1) {
            servo.write(pos);
            delay(15);
        }
    }
}

void blinkLED1() {
    LED_1_STATUS = !LED_1_STATUS;
    digitalWrite(LED_1_PIN, LED_1_STATUS);
}

void blinkLED2() {
    LED_2_STATUS = !LED_2_STATUS;
    digitalWrite(LED_2_PIN, LED_2_STATUS);
}

When I flash this to the Due, two disappointing things happen:

The LEDs, which previously blinked at the correct rates, now stay lit and do not blink at all; and
The servo doesn't move

Now perhaps I have a bum servo, or perhaps I haven't wired it up correctly, but the most concerning thing to me is that the LEDs are no longer blinking. I have a feeling that once I get those blinking again, the servo will probably start sweeping as well.

Can anyone spot anything that jumps out at them as being wrong here, wiring and code alike?

One thing that immediately jumps out at me is you are trying to power the servo from a digital pin.  That is very very wrong.

The servo must be powered from the +5V pin (or +3.3V pin if it's a 3.3V servo) and only the "pulse" pin is connected to an Arduino's PWM capable IO pin.

Also, I don't know how the "Threads" library works, but it looks to me like it's not real threads, but a "round robin" execution of function with time delays.  If one of your functions never returns (like your servo one) then the whole system will lock up.  You need to make your servo function non-blocking like your LED functions.  Give it a 15ms time setting and only move one step of the servo each time it gets called.

Ok, according to comments and research I can confirm that in fact the Thread library is really badly named.  It doesn't run threads, it just runs different functions at different times.  Those functions MUST be "single shot" - i.e., they MUST complete before anything else can happen.  There is absolutely no concurrency whatsoever.  It is entirely up to you to ensure that all your "threads" are fairly simple repetitive operations which are to be run at specific points in time.

Basically the operation is thus:

Add a function and its time to a list.
Work through the list to find a function whose time has expired
Call that function
Continue through the table
Go back to the beginning

If you have two functions both with the same time then one function will be called first and execute to completion, then the other function will be called afterwards, to execute to completion.  Only when a function returns is the system able to move on to the next entry in the function list.

You must not use delay() in your "thread" functions for anything more than maybe 1-2ms of delay in total.  You MUST return from your thread with enough time for your next timed event to execute, otherwise it will be delayed, or never run at all.

So your servo thread would look something like this:

Add my current "direction" to the servo value
If the servo value < 0 or > 180 then invert the direction and limit the value to 0-180.
Write the value to the servo

That is then triggered every 15ms by the thread library.

So as real code it may look like:

void runServo() {
    static int direction = 1; // 1 = up, -1 is down
    static int value = 0;

    value += direction;
    if ((value <= 0) || (value >= 180)) {
        direction = 0 - direction; // Change direction from + to - or - to +
    }

    value = max(min(180, value), 0); // Clamp it to between 0 and 180

    servo.write(value);
}


How to initialize and run PCA9685? I'm trying to write a simple code for initializing and running the PCA9685. I tested the board with Adafruit library and it's working.

But I just want to develop a simple code to include it in my various modules library for future projects.

I wrote a code, but I think I'm not understanding the work of the internal registers.

But according to the datasheet I configured only the auto increment and left the rest to default settings. Then I headed up to the last registers which are the all_led_on and all_led_offas wanting to run the outputs on/off to blink the LEDs. But I think these two registers are for enabling/disabling the pins. Is that right?

This is my code:

void pca9685_init(void){
    uint8_t i,val[]={0x20,0x04};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_MODE1);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

void pca9685_all_on(void){
    uint8_t i,val[]={0x00,0x10};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_ALL_LED_ON_L);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

void pca9685_all_off(void){
    uint8_t i,val[]={0x00,0x10};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_ALL_LED_OFF_L);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

The registers aren't for just turning the LEDs on or off.  They are for setting the ON and OFF times of the PWM. Bit 12 of each combined value is used as a "full" setting, so:

To set the LEDs on to full brightness you need to set:

PCA9685_ALL_LED_OFF_L to 0x00
PCA9685_ALL_LED_OFF_H to 0x00
PCA9685_ALL_LED_ON_L to 0x00
PCA9685_ALL_LED_ON_H to 0x10

This sets the off time to 0 counts and the on to be "full on".

It doesn't really matter what value you set the OFF to as long as you set ON to "full on" and off isn't set to "full off".

For off you should set the ON to 0 and the OFF to "full off" (reverse the above settings).

Section 7.3.3 of the datasheet says:

  The turn-on time of each LED driver output and the duty cycle of PWM can be controlled independently using the LEDn_ON and LEDn_OFF registers.

  There will be two 12-bit registers per LED output. These registers will be programmed by the user. Both registers will hold a value from 0 to 4095. One 12-bit register will hold a
  value for the ON time and the other 12-bit register will hold the value for the OFF time. The ON and OFF times are compared with the value of a 12-bit counter that will be running
  continuously from 0000h to 0FFFh (0 to 4095 decimal).

  Update on ACK requires all 4 PWM channel registers to be loaded before outputs will change on the last ACK.

  The ON time, which is programmable, will be the time the LED output will be asserted and the OFF time, which is also programmable, will be the time when the LED output will be
  negated. In this way, the phase shift becomes completely programmable. The resolution for the phase shift is 1⁄
  4096 of the target frequency.

So you have to set all 4 registers together for anything to happen.

There are also some examples shown in the datasheet as well which explain it better.

In simple terms:

There is a free-running counter that counts from 0 to 4095
When the ON time matches the counter the LED turns on.
When the OFF time matches the counter the LED turns off.
If a channel is "FULL OFF" it will be off regardless.
If a channel is "FULL ON" and not "FULL OFF" it will be on regardless.
"FULL OFF" always takes priority over everything else - even "FULL ON".

Some simple examples:

All off: ON=0x0000 OFF=0x1000
All on full: ON=0x1000 OFF=0x0000
50% duty: ON=0x0000 OFF=0x0800
25% duty: ON=0x0000 OFF=0x0400
25% duty with phase shift: ON=0x0100 OFF=0x0500


Arduino & ARM - Replacement for avr-libc? There is very cool avr-libc library that provides direct access for all functions of AVR microcontrollers. I'm writing a project for Arduino Due and I want to use timers and ISRs directly. Is there a library like avr-libc for ARM Cortex M3?

I think newlib is the one you want.
howto


Can I convert 3.7V to 5V's using 3.3v to 5v converter THe product: (https://www.sparkfun.com/products/12009)

So guys, here' s a pretty simple but important question for me:
Can I convert 3.7V (li-po battery's voltage level) to 5V's (I do have arduino pro mini running on 5 volts) using 3.3v to 5v converter (picture shown above...) ??

Thanks already...

No. That is a level shifter. It uses a low voltage (3.3V) to switch a separate high voltage (5V) supply to create different logic levels.

It does not convert voltage, it merely switches.

To create 5V from 3.7V you need either a boost converter (inductor based circuit) or a charge pump converter (capacitor based circuit).


Cheapest Arduino wireless solution for home automation I am from programming background and newbie to this field.

Couple of days ago I brought Arduino Uno (5V). I want to control light bulb and fan from my Android. So I thought, I will buy relays and ESP8266 module and its done.

But now read somewhere that ESP8266 works with 3.3v and my Arduino supplies 5v.

Should I go for different Arduino board (like Arduino pro or Arduino mini) or is there any reliable & cheap solution that will work my Arduino Uno (5V) ?

If you want to go for cheap just use a ESP8266 no arduino needed.


Using ESP8266 Adapter with Temperature/Humidity Sensor Good Day. I am currently following a project where I can send data to my firebase database using an ESP8266-ESP01 wifi module and DHT11 temp/hum sensor.
I am using this adapter to enter the boot mode already with a program. Everything seems fine.

When I need to upload a program I am just tweaking the adapter using jumper cables to put the GPIO0 to GND and It works fine. My problem now is I have to use the DHT11 Sensor which is supposed to be connected to GPIO2. I tried to go to bootmode so  I connected DHT11(data) directly to the ESP8266(GPIO2) leaving the slot in the adapter empty in which I cant enter the boot mode for some reason.

But when I plug ESP8266(GPIO2) to the adapter slot, I can enter bootmode. Currently confused on how to tweak the adapter to be able to use the GPI02 to the DHT11. Any tips would really help. thanks!

Thank you everyone for the tips. I have found a way to use the esp8266 adapter with the DHT11 sensor. First of all it was on boot mode all along, I had some code mistakes where my target url includes an 'https' tag on it thus not functioning as expected.

For those who would like to use this specific adapter with DHT11 attached in boot mode.

-Connect all female jumper wires end to the Esp8266 and the male jumper ends to the adapter except for the GPI02.

-The GPI02 slot on the adapter will be empty but the ESP8266 GPI02 end must be connected to the data pin of the DHT11.

Make sure that the ESP8266 and DHT11 sensor have enough power for both devices.


Tinyduino I/O line voltage level Does anyone know what the I/O line voltage level is on the Tinyduino?

Tinyduino

I want to run a MAX7219 LED array with it, like this one:

LED Array

Whatever your power supply voltage is. If you run it from 5V you get 5V IO. If you run it from a 3V coin cell you get 3V IO.


How to find out if HX711(amplifier and 24-bit ADC) is damaged or not? I'm using this ADC with a load cell for weight measurement, I had 4 strain gauges and mounted them on a cantilever structure that I made out of acrylic sheet, used calibration program from here: https://github.com/olkal/HX711_ADC/blob/master/examples/Calibration/Calibration.ino,
followed the steps but it gave calibration factor as 0.00 and the output was NaN or inf . I used another program from here: https://github.com/queuetue/Q2-HX711-Arduino-Library/tree/master/examples/simple_scale and the output was just hovering around 83868. So I thought that the mounting was the problem and used a load cell (green label, CZL 601) with the above and found the same results by doing the above.
Then I thought maybe the ADC is at fault , measured the power output from Arduino to the board and it was around 5 V , but when I measured between the E+ and E- , I got 0 V. Since it is the excitation voltage to the bridge, it should be around 5V too right?
Is this the right way of checking the board?
P.S. I measured the four wires of the load cell and connected the opp. ends of the bridge to the E+ , E- , A+ , A- (order doesn't matter here right? connected the pairs that showed the rated resistance to E's and A's separately)
Here's a [pic][1] of the connections
Between White and green wire the Resistance is 350 ohm
Between Bk( connected in the board ) and the red it is 408 ohm
Between White and red it was 263 ohm
Between white and bk it is 320 ohm
Between bk(not connected in the board) and all others it is around 1 MOhm (so ignored that)
[1]: https://photos.app.goo.gl/4HEmZaN1EwZ7Mjur7

Looking closely at the photo of your setup I can see that you haven't soldered the header to the breakout board. Whilst there are headers available that don't require soldering, and ways of making header connections that don't require soldering, this isn't either of those.
Without solder the connection to the board will be intermittent at best and non-existent in general.


Wirelessly (but fast) transfer STEP and DIR output from Arduino to stepper driver Very short version:
Looking for a way to wirelessly get STEP and DIR signals (only those two signals) from an Arduino to a DRV8825 stepper driver about a meter away:
Arduino -> STEP and DIR IO pins -> transmitter ) ) ( ( receiver -> DRV8825

Long version:
For a project I've mounted an Arduino to a wooden board. The Arduino has a GRBL shield (basically a breakout board to four motor drivers for stepper motors (in my case the DRV8825)). Connected to this setup is a stepper motor. The power supply (NOT on the wooden board) for the motor is 24v, and I'm using a buck converter to take it down to 5v for the Arduino.
This whole board is rotating and the 24v gets passed to it using a custom sliding-contact with two contacts (24v and gnd).
Now this all works fine, but the problem is this: I have a second motor which I want to control from the same GRBL shield. But this motor is NOT on the rotating board.
If I place the motor driver next to this motor and power it from the same power supply (parallel to the sliding-contact) I have everything I need, except for the STEP and DIR signals from the Arduino.
Because there is no way I can add 2 more contacts to the sliding-contact (plus the signal would probably be too noisy anyway) I'm looking for a way to basically add a wireless bridge between the STEP and DIR output pins on the Arduino, and the STEP and DIR input pins on the motor driver. The motor and driver are about a meter away from the Arduino, so signal strength shouldn't be a problem.
I believe those well known 433Mhz transmitters are too slow for something like this, but I read most nRF24L01 modules are faster. Before I order some for a test setup, I was wondering if anyone already knows if this could work or not, knows a useful alternative, or has some suggestions for keywords to search for when trying to find another solution. I can find a lot of 'wireless' motor drivers online, but most are completely standalone units where the microcontroller is on the board, it's just controllable over wifi/bluetooth.

(Moved to "answer" for space; it's definitely not an answer. Sorry all!)
Minor points:

It's a motor controller shield; the GRBL is on the Arduino.
You'll need a motor controller at each motor; not clear if that's understood.
I'd also consider optical comms, although it has a different set of problems.

Ultimately I might approach this in a different way: instead of a single GCode box attempting to synchronize and control itself and an (essentially) independent system, I'd consider having a single GCode box (GBOX) controlling two independent systems (M1, M2).
GBOX would be a laptop/RPi/whatever that processes the "real" GCode. Based on the GCode commands, which in the end just tell motors what to do, I'd send each GCode command to its associated M1/M2 system.
How well this works depends a lot on the GCode, however; diagonals, arcs, etc. require motor cooperation, so a command like G02 X2Y0 R2 might cause problems, even though we can pull out the X and Y data. How the GCode is generated matters, but note that GBOX could also interpolate "tricky" commands to break them into something a dual-target system might be able to understand.
The "meaning" of the moves also matters: there's "getting from one place to another" and "getting from one place to another while drawing a line": the former may (or may not) have requirements around what that actually means, while the latter requires coordinated motion, and even if you're splitting the commands up correctly, even a fraction of a second difference in receive/action time will matter. Of course, you could also transmit both motors' commands to both motors and rely on timing or cross-Mn synch for starting their respective commands.
In the end it may be the only real way to make this work would be to have the "independent" systems be able to synchronize with each other, so that they know they're (a) ready to start, and (b) starting at the same time. GBOX could also potentially handle that synchronization as a "Go!!!" command is about as deterministic as it gets, especially if M1/M2 can receive a broadcast signal at the same time.
https://www.zikodrive.com/motor-control-case-studies-and-applications-2/a-remote-controlled-and-synchronised-stepper-motor-controller/ (very) briefly discusses the issues around synchronizing remote motors where their relative positions matter.


How to handle concurrent HTTP request when using interrupt I'm trying to make a door sensor with a reed switch. Each time the there is a change, the ESP8266 sends an HTTP request to web service.

Unfortunately, the ESP8266 serial monitor dumps a huge stack trace when I'm approaching the magnet to the reed switch:

Exception (9):
epc1=0x40104b14 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000003 depc=0x00000000

ctx: sys
sp: 3fffeb20 end: 3fffffb0 offset: 01a0

>>>stack>>>
3fffecc0:  00000002 00000006 3ffefdc4 40227108
3fffecd0:  3ffefa74 00000002 00000014 401004e4
3fffece0:  3ffeffbc 3ffeffc0 00000006 00000001
3fffecf0:  402253bc 00000000 00000010 00000000
3fffed00:  00000000 4bc6a7f0 81cac083 00000000
3fffed10:  00000000 00000000 4bc6a7f0 00000000
3fffed20:  40104d40 0037d809 3ffeecd0 00000000
3fffed30:  3ffee520 3ffeecd0 3ffeffbc 40224398
3fffed40:  00000000 00200085 40201578 00001388
3fffed50:  3ffeecd0 00000000 00000050 00000050
3fffed60:  00000000 3fffedd0 3ffefd34 402032e5
3fffed70:  1301a8c0 00000031 3ffeebbc 402039cc
3fffed80:  3ffeedb8 000000ef 000000ef 00000020
3fffed90:  ffffffff 00000050 3fffedd0 40202d5c
3fffeda0:  40204738 1301a8c0 40204738 1301a8c0
3fffedb0:  3ffe8a64 00000005 000...

I think it's because the ESP8266 tries to make concurrent HTTP calls...
How can I solve this?

Here is the code:

// https://www.instructables.com/id/Arduino-Software-debouncing-in-interrupt-function/
// #include "util/atomic.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "Wire.h"

const char* ssid = "****";
const char* pass = "****";
const byte interruptPin = 5;
long debouncing_time = 50; //Debouncing Time in Milliseconds
volatile unsigned long last_micros;
const char* host= "192.168.1.19";
const char* doorStates[2] = {"closed", "opened"};

void connection()
{
  // Establish a WIFI connection
}

void setup()
{
  Serial.begin(115200);
  connection();
  pinMode(interruptPin, OUTPUT);

  // Attaching interrupt
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE);
}

void loop()
{
  delay(1000);
}

void handleInterrupt() {
  if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
    int val = digitalRead(interruptPin);
      notify(val);
  }
  last_micros = micros();
}
// Make HTTP Call to web service
void notify(int val)
{
  WiFiClient client;
  const String frontDoorState = doorStates[val];
  String url = "http://192.168.1.19/alarm/front-door/state/" + frontDoorState;
  client.connect(host, 80);
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: 192.168.1.19\r\n" +
                 "Connection: close\r\n\r\n");
                 client.stop();
}

Simple: don't do HTTP requests in the interrupt.

It's usually bad to do anything heavy like that in an interrupt.  Instead you should just set a flag in the interrupt (volatile bool) and examine that flag in loop().

volatile bool sendNotification = false;
volatile int notifyVal = 0;

void loop() {
    if (sendNotification) {
        notify(notifyVal);
        sendNotification = false;
    }
}

void handleInterrupt() {
    if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
        notifyVal = digitalRead(interruptPin);
        sendNotification = true;
    }
    last_micros = micros();
}


hexadecimal 1 to float 1 - Compare the float 1 with a predefined float 2 - If the float 1 and float 2 are the same - Print hexadecimal 2 I want to input a hexadecimal data from cool terminal say like (05 00 02 03 00 04 00 E5) And convert the data to a float value say 45.3. Now that I have to preassign a float value say 45.3 in my program so that I can compare the converted float value with the preassigned float value. If the two values match I need to print another hexadecimal value i.e( 05 03 00 01 00 02 04 4F).

I have managed to do the conversion of hexadecimal to float. Can someone please help me in comparing the two float values?

Comparing floating point values is notoriously difficult. This is because floating point is only an approximation.

You should first define an error margin - a value which is how close together the two values need to be before you consider them to be the same.

For example 1.000000 and 1.000001 could be considered to be the same value in many circumstances.

The simplest method is to just subtract one value from the other, take the absolute value of the result, and see if it is below the error margin.

bool almost(float a, float b, float margin) {
  float diff = fabs(a - b);
  return (diff < margin);
}


Arduino Yún causing power suge warning Recently I got an Arduino Yún board that sends out a power surge error message everytime I connect it to my laptop through the USB cable. I tried two Arduino Leonardo and one Arduino Uno and there wasn't any problem with them or the USB port. Am I missing something or is the board faulty already?

Use a USB tester to test the current consumption, it should be < 500ma
I recommend using a USB that has power of its own, eg. monitor USB


Need help with the basics on serial control I am struggling to get my head around why this just won't work. In my simple mind this simple sketch should do as it's told. But I am obviously missing something fundamental.

If anyone could shed some light on what I am doing wrong that would be very good!

The sketch is just to control a relay by typing on or off into the serial monitor. However although it uploads, all I get is the Serial.println repeating and no action on the physical relay.

I can manage to control things over serial by using the switch, case statements but I wanted to try it using full words rather than single chars and also using IF statements etc.

Thanks in advance!

EDIT
I just changed the string inputs to a char input and serial.readstring to just serial.read and it works with just entering a 1 or a 2 for example. So to re-ask my question - how can I get it to respond the same but using words? Thanks!

int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  Serial.println("To toggle relay enter on or off");
  while (Serial.available()==0) {}
  serialInput = Serial.readString();
  if(serialInput=="on") {
    digitalWrite(relay, HIGH);
  }
  if(serialInput=="off") {
    digitalWrite(relay, LOW);
  }
}

You are assuming that Serial.readString() will magically know how long a string you meant to send, and wait until it's all there.  It doesn't guarantee that.

If your PC uses Linux or Mac, you can use Serial.readStringUntil('\n'), which will read until a line end, and send on<ENTER> as your command.

If you use Windows, the line endings are \r\n so it's a bit more awkward.  Build up your string piece by piece, perhaps

int relay=8;
String serialInput;

void setup() {
  Serial.begin(9600);
  pinMode(relay, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();   // get one byte from serial buffer
    if ('\r'==c || '\n'==c) {
      // End of line - process the string
      if(serialInput=="on") {
        digitalWrite(relay, HIGH);
      } else if (serialInput=="off") {
        digitalWrite(relay, LOW);
      }
      serialInput = "";
    } else {
      serialInput += c;     // add it to readString
    }
  }
}

Brief description of how it works:

The string SerialInput starts empty.  We do the following repeatedly:

If there is a character available on the serial port, read it.
If it is not an end-of-line character, add it to the end of our string
If it IS an end-of-line character, we know we've got to the end of the line, so...

check whether it matches one of our "target" strings, and act on it if so
clear it back to an empty string


ST7735 display with esp32 I have edited the adafruit ST7735 library so that it supports esp-32.I made some edits in Adafruit_ST7735.h file. which are as follows.

The code works fine but I had expected the screen to work faster with esp-32(due to higher processing power) but it does not do that.

I checked the time for fill screen operation for esp-32 and arduin mega. They come out to be almost the same. (around 0.12 seconds). Can anyone explain why this is happening and can I increase the speed?

The ST7735 uses SPI to communicate. It will always be slow compared to parallel connected screens.

The fact that you appear to be using bitbanged SPI (manually toggling IO pins) makes it even slower.

The fastest you will be able to get with that screen will be to use hardware SPI instead (which most likely limits which pins you can use - I am not familiar with the ESP32 though) but that will still be somewhat slow.

If you want really high speed screen updates then you will need a parallel interface screen, ideally a 16-bit parallel interface screen. However, for that you need around 20 IO pins to drive it.


Flashing ESP8266 over WiFi whith samrtphone? I'm working on a project in which an ESP8266 is the brain of the device. I want to add new features to the device controller later but this requires that the user open the controller and reprogram the ESP8266.

I want the user to be able to update the firmware with his smartphone (maybe through an application). How can I do that? Is this possible with this chip?

ESP8266 OTA can be performed through a web browser as detailed in the ESP8266 OTA information page.

Since a smartphone has a web browser I can see no reason why you can't use that.


ATmega328P SPI Slave I was scrolling through the ATmega328P datasheet when I came across a rather fascinating statement about the way in which the data part of the SPI interface is buffered. I can't seem to understand why the double input buffer is necessary. The following statement can be found on page 161 (Datasheet):

  The system is single buffered in the transmit direction and double buffered in the receive direction. This
  means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle
  is completed. When receiving data, however, a received character must be read from the SPI Data
  Register before the next character has been completely shifted in. Otherwise, the first byte is lost.

Can someone please briefly explain to me why the double input buffer is necessary?

You have control over when you place a byte in the TX buffer and control over when you read a byte from the RX buffer. You don't have control over when the master sends data to you, though, so somewhere is needed to store that incoming data until you read it. Since the master can start sending another byte before you have read the last one it's critical that the receiving shift register is separate from the register you read the shifted in data from.  Only when the complete byte has been shifted in does it get copied to the receive buffer, so that another shifting in can begin.

When transmitting you don't need to worry about that since what you write into the TX buffer is what is about to be shifted out. You don't write anything else until it's time to send the next byte, at which point the TX register is empty anyway.


Using an external interrupt alongside serial I want to read data from an accelerometer sensor, which pushes its data to the Arduino via an external interrupt. I then want the Arduino to relay this data to a host computer via the serial connection.

Will the external interrupt interfere with the serial connection? If the Arduino's in the middle of transmitting via serial, and the accelerometer triggers the interrupt, won't that potentially break the serial connection?

Transmitting a single character via UART on the ATmega328P (and all other AVRs with a dedicated USART) cannot be interrupted since it is independently clocked. Loading the next character into the transmit buffer can be (since the INTx interrupts have priority over the USART,xxx interrupts), but this will not actually break communications, just slow it down.


Which sensor to detect light? I have a kit of 37 sensors as described here:

http://www.instructables.com/id/Arduino-37-in-1-Sensors-Kit-Explained/?ALLSTEPS
https://tkkrlab.nl/wiki/Arduino_37_sensors

I want to create a simple circuit:

if the light is detected - flash LED
if there is no light - do nothing

Among 37 sensors I don't seem to find anything related to light / brightness / lumens...

Can you please advise me which sensor to get?

Shall I get a photocell  (Light Dependent Resistor) as described here: https://learn.adafruit.com/adafruit-arduino-lesson-9-sensing-light/parts ?

Number 23 in the list says photoresistor, corresponding to module KY-018 in your kit, which is what you called photocell (a photocell is another type of sensor to my knowledge).
As the name states, a photoresistor is a device changing it's resistance depending on the amount of light it detects/receive.

A photoresistor usually looks like:

In order to get a meaningful reading from an LDR you need to convert the resistance into a voltage which the Arduino's ADC can read. The simplest method is to use a voltage divider: the junction between the LDR (photoresistor) and R1 is the node to connect your analog pin to get your readings, which will be a voltage that is a proportion of the supply voltage (5V) defined by the ratio of the two resistances.

The KY-018 module mentioned above already provides all the necessary and provides you 3 pins: 5V, ANALOG and GND.

simulate this circuit – Schematic created using CircuitLab


How to repair or work around a damaged usb port on the Arduino? While unplugging the usb cable from the Arduino, the plastic piece in the center of the port (the part that separates the pins) broke off and lodged into the end of the usb cable. I didn't notice that it broke off and when I plugged the cable back into the Arduino it bent one of the pins back onto itself.

How would you go about repairing this?

If I fail to repair it is there an alternate method to programming the board?

You would need to replace the whole socket in order to repair it. For that you would need:

Soldering iron
Solder sucker
Solder wick
Patience and experience

Or you just connect an FT232 breakout board to TX, RX and RESET as if you were making a breadboard arduino and program the board through that.


Arduino Analog Input: why the weird fluctuation? I am using an Arduino Uno. analogRead(A0) (or whichever channel I use) returns 0 when it is grounded with Arduino Gnd, and 1023 when connected to Arduino 5v. But when I connect it to a current sensor (ACS712) it is always fluctuating like this:

  0, 0, 0, 0, 0, 0, 1023, 1023, 1023, 1023, 1023, 441, 446, 0, 0, 0, 0, 1023, 1023...

I also tried it with a potentiometer (10K) and analog joystick: the results are the same. I tried changing different power supplies (both Arduino's and the sensor's (ACS712, potentiometer, joystick)). I even tested it on an Arduino Mega, but no luck. Such extreme fluctuation are making no sense to me. Kindly help me what could be the issue.

My wiring diagram is attached to this post. And I use an external supply to the ACS712. Is it possible that Static electricity is causing this issue?

Code:

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

void loop() {
  float value = analogRead(A0);
  Serial.print("Raw:");
  Serial.println(value);
  delay(500);
}

Thanks.

You need to connect together the grounds from your external power supply and the Arduino.

At the moment the two devices are floating - there's no commonly-agreed 0v point.


Schematic for the adafruit motor shield v2.3 I am trying to locate a schematic for the Adafruit motor shield v2.3. It has many ports and currently I have found little to no explanation of what is on the board. I located this picture which highlights the motor ports, servo ports, and Arduino Pins. But what about everything else?

What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins? What is the PWMs 0,1,14,15? How is the big empty board in the center setup?

Everything can be found out by reading the schematic which, incidentally, is the first hit on Google when you search for "Adafruit motor shield 2.3 schematic":

  What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins?

Yes. They're just there to make it easy to solder wires and jumpers to.

  What is the PWMs 0,1,14,15?

They are connected to PWM pins 0, 1, 14 and 15 of the PCA9685.

  How is the big empty board in the center setup?

It's just holes. Known as a "matrix prototyping board" for you to solder your own components and things into. Nothing there is connected to anything at all, it's up to you to make the connections with solder and wires.

As you can see from the schematic the only Arduino pins used are SDA/SCL (A4 and A5) and two PWM pins D9 and D10. Everything else comes from the on-board I2C PWM chip.


Unable to upload the data on thingspeak using uno and esp8266 I am able to connect to thingspeak but now able to upload the data. here are my set of commands:

AT+CIPMUX=0
OK

AT+CIPSTART="TCP","184.106.153.149", 80
OK
Linked

AT+CIPSTATUS
STATUS:3
+CIPSTATUS:0,"TCP","184.106.153.149",80,0
OK

AT+CIPSEND=45
> GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60

busy s...

SEND OK

OK

and after some time unlink

I am giving these commands using arudino serial monitor.
Please help, I have searched a many blogs, youtube videos.

You have a malformed HTTP request. You only have half of the first line.

A valid HTTP request would look more like this:

GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60 HTTP/1.1
Host: api.thingspeak.com
Content-length: 0
Connection: close
<blank line>

Just sending "GET : ain't gonna work. For a start, the server won't know what protocol you're speaking (HTTP/1.1), nor what website it's supposed to direct the request to (Host: api.thingspeak.com). Also, the final extra blank line is required to finish the request.


Measuring ADC sample rate - Arduino DUE I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode. Hints are welcome, I really don't know where to start.

Measure how many times per second was main loop called:

bool secondPassed()
{
  static long lastTick = 0;
  long now = millis();

  if (now <= lastTick + 1000)
    return false;

  lastTick = now;
  return true;
}

int counter = 0;
void loop()
{
  analogRead(A0);
  counter++;
  if (secondPassed())
  {
    Serial.println(counter);
    counter = 0;
  }
}


error using String class to convert a double to a string i wanted to convert a double to a string i tested several examples online i allawys get the same error.

the code :

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

}
void loop()
{
  double val =3.2222;
  String stringOne =  String(val, 3);
  Serial.print(stringOne);
}

the errors :

sketch_jun02c.ino: In function ‘void loop()’:
sketch_jun02c.ino:10:36: error: call of overloaded ‘String(double&, int)’ is ambiguous
sketch_jun02c.ino:10:36: note: candidates are:
In file included from /usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:192:0,
                 from sketch_jun02c.ino:2:
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:70:11: note: String::String(long unsigned int, unsigned char)
  explicit String(unsigned long, unsigned char base=10);
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:69:11: note: String::String(long int, unsigned char)
  explicit String(long, unsigned char base=10);
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:68:11: note: String::String(unsigned int, unsigned char)
  explicit String(unsigned int, unsigned char base=10);
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:67:11: note: String::String(int, unsigned char)
  explicit String(int, unsigned char base=10);
           ^
/usr/share/arduino/hardware/arduino/cores/arduino/WString.h:66:11: note: String::String(unsigned char, unsigned char)
  explicit String(unsigned char, unsigned char base=10);
           ^

I had installed arduino using apt-get and I didnt notice that I had an old version. I upgraded my arduino and it worked fine.


How to read AC Voltage in arduino uno with 12V adaptor and usb cable.? i want to ON-OFF two lights(white and red), one from main power source(white light) and one from ups(battery). When main power is present, white light should be ON and red should be off. And when main power fails, red should be ON and White should be OFF.
I have Arduino, usb cable, external power supplier(adapter of 12V).

Can any one please suggest me how do i proceed for this ??

If your battery voltage is lower than 12 but sufficiently high to power the arduino (let's say 9V), you could put a white LED on the 12V line and a red LED on the battery line, like this:

         WHITE       RED
  _______|>|_________|<|________
 |             |                |
_|_          Arduino           _|_
 - 12V         |                -   Battery
 |_____________|________________|

This should work, as long as the LEDs can withstand the reverse voltage.
And you do not need to drive them from the Arduino.
If you still want to know the status fro mthe Arduino (mains or battery) you can sample the voltage level across the Arduino.


Can I use LiFe PO4 batteries in a 18650 battery shield? Is it safe to use LiFe PO4 batteries in a 18650 Battery Shield (sometimes called Lithium-Battery Shield)?

In my opinion it is NOT SAFE, if your 18650 Battery Shield also charges the battery.
Anyhow some pages state that it is possible to charge LiFePo4 batteries with 4.2V instead of the recommended 3.65V. https://www.powerstream.com/lithium-phosphate-charge-voltage.htm
LiFePo4 batteries have a smaller energy density and therefore capacity. Thus those are not as explosive as Li-Ion batteries. But you are risking damaging the battery and shorten its lifespan.


How do you use an Arduino to control a 4 - 20 mA transmitter? I am using an Arduino Mega to control the speed of an AC pump. This can be done by connecting to the variable frequency drive. Here is a link of the relevant datasheet, pages 66 and 67 relate to what I am doing.

http://www.parker.com/Literature/SSD%20Drives/AC%20Drives/AC650/HA464828U003.pdf

From what I have read and been told already, I should be able to control this using a 4 - 20 mA loop, which is fed into AIN2, as long as I connect the 0V terminal as well?

My question is what is the best way to make a current loop transmitter using an Arduino Mega.

So far the options I have are:

Create a circuit out of discrete components, this would then be controlled using the Megas PWM
Use an IC circuit, I was looking at the AD694JNZ
Use an add on board, I was looking at this one: http://uk.rs-online.com/web/p/products/8828929/?grossPrice=Y&cm_mmc=UK-PLA--google--PLA_UK_EN_Semiconductors-_-Semiconductor_Development_Kits&mkwid=sm9dTYvCc_dc|pcrid|88057061283|pkw||pmt||prd|8828929&gclid=CjwKEAjwk6K8BRDM3aCSkdCtzSQSJAA3Vf38mNs9lZrg2A1AjrVpS3SCubT0AbAr7L8OImUZbfCPzRoCIXjw_wcB

I have a budget for my project so cost is not an issue, however I am running out of time. What would be the easiest method to implement and how?

I have been thinking of using options 2 or 3, however my issues are that this is my first Arduino project. I understand what PWM is but I don't know how I would go about implementing it. I also can't find any tutorials online that demonstrate how to program the MIKROE board using an Arduino.

Thank you in advance for any help :)

I can recommend the Click boards from MikroElektronica (I am the chief engineer porting support for them, and the PIC32-based Clicker development board series, to the chipKIT™ system).

The 4-20mA-T Click board is controlled by the Microchip MCP4921 DAC. This is a common DAC family used in many Arduino projects and there are plenty of libraries around for them (mine is here though it's aimed at the 4822 not the 4921).

Basically you set the DAC output voltage which sets the current output from an XTR116 current loop transmitter.

The XTR116 takes an input of 0 - 4.095v, and provides a convenient 4.095v reference voltage to the MCP4921.

Datasheet for the XTR116
Datasheet for the MCP4921
Manual for the 4-20mA T Click

The whole thing is isolated from your main board through an ADu M1411 to keep everything safe from industrial process noise.


Matching baud rate on serial monitor I am using different codes which set different values of baud rate through the Serial.begin() function. Do I need to change the baud rate of the serial monitor to match the initialized value on the code I am running every time, or can I just leave the serial monitor baud rate set at the highest frequency of all my sketches (115200)?

If your sketch has

  ...
void setup() {
  Serial.begin(115200);
  // ... other stuff here;
}
  ...

And you run the IDE serial monitor at 9600, you will get gibberish. The same happens the other way round. You need to match the monitor to the baud rate you've defined on the Serial.begin(); call.


Using Serial.begin() twice I'm training kids programming Arduino. We're gonna use Serial for debugging purposes, so we started with a simple HelloWorld program. I let them try various stuff, including changing the speed.

Now, one of the outcomes was as simple as

void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.begin(9600);
  Serial.println("world");
}

My expectation was, that the Arduino does exactly as written, but the serial monitor of the Arduino IDE will become a bit consufed. When the monitor is set to 115200 baud, I expected to see

Hello
world
_#&%$"    < some garbage
world
_#&%$"    < garbage again
...

However, the real output is only one line

H⸮⸮⸮⸮C

Why is that? Is it impossible to change the baud rate in between?

The official documentation does not say we can use Serial.begin() only once.

I'm using Arduino Uno and Arduino IDE 1.8.9

This is because the output of the serial is buffered. It's still sending the first bit of data while you change the baud rate - and from then on it's just a complete mess.

You need to force it to finish sending before you can change the baud rate by using Serial.flush():

void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
  Serial.flush();
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.flush();
  Serial.begin(9600);
  Serial.println("world");
  Serial.flush();
}

That will wait after each print until all the data is sent out "onto the wire" before changing the baud rate for the next print.


Differences between Arduino IDE versions I run Arduino IDE on both my Mac and under Raspbian on a Raspberry Pi, both running the latest version of OS.

The Raspberry Pi has Arduino 2:1.0.5+dfsg2-4.1 and I am running the latest 1.8.4 on macOS.
Debian is always somewhat behind the latest software, and this has not concerned me before, as I have never had issues before. (I know I could download the latest ARM32 build or compile from source, but this would probably generate a lot of dependencies.)

I have recently run into a couple of problems.
Compiling a script which has #include <SdFat.h> generates an error, although the library is present in ~/sketchbook/libraries/SdFat/src/SdFat.h. This does not seem to be an issue on macOS.

I was also trying to program an Atmega using a Uno as ISP as in "Using an Arduino as an AVR ISP". I have done this in the past, but the instructions and the Arduino program seem to have changed; there is no longer "Upload Using Programmer" menu, but suggests the "Burn Bootloader" command. Does this upload both the Bootloader and Sketch?

Debian is always somewhat behind the latest software

No, when it comes to the Arduino IDE Debian is frozen on an ancient version.

1.0.5 is considered to be too old to use. Many many things have changed since then - bug fixes, optimisations, new API components. And not least the implementation of the Board Manager for installing support for more boards, both by Arduino and other makers, and support for multi-arch libraries (which your SdFat library is with a src folder in it).

You should never install the Arduino IDE from the Debian repositories. Instead you should download the current version of the Arduino website (http://arduino.cc/download) as a tar.\z file and extract it into a folder and run it from there.


Control DC motor in both directions with two relays I am using an Arduino and two relays to control 12V DC motor.
I need to rotate the motor in both directions.
For the first trials it worked fine. Finally one next switching fried my Arduino.
I think there is something wrong in the schematic.
I believe that Arduino was killed by reverse voltage spike produced by motor.
I already know that I need a diode across the motor. However, I have two directions here.
So, what is the proper schematic for my task?

In short, you're probably overloading your regulator.
It's difficult to say for sure, but I have a suspicion and can give a framework for thinking about it with some very crude numbers.
If you're powering the Nano from a 12 V source, you are dropping 7 V across the regulator.  If you do the math on this 7 V drop, it means every 14 mA drawn through the regulator induces nearly a tenth Watt of heat in the regulator.  7 V * 0.014 A = 0.098 W.  I'm guessing you have a budget of perhaps 300mW based on the way the Nano's regulator is set up.
The ATmega328P says it uses 5.2 mA (typical) or 9 mA (maximum) at 5 V and active at 8 MHz.  But really it will use more at the 16 MHz frequency.  For sake of argument, I'm just going to say it's using 14 mA, because it makes the math easy and because power usage scales somewhat linearly with frequency.
Just the power led will use about 3 mA, if it's an official Nano, but for simplicity sake, I'll call it 7 mA, being half of 14 mA and we'll ignore the fact that there are other loads on the board like the serial transceiver.
Your relay coils will use at least 30 mA, but likely more, perhaps a lot more.  But for ease of calculation lets go optimistic and say they only use 28 mA (cause 2 * 14 mA).
So we have the ATMega328P inducing 100 mW in the regulator, the power led and some extras adding 50 mW. at at least one relay coil energized for another 200 mW.  So right there you're already at 350 mW.  If you screwed up and managed to energize both relays, 550 mW.  Hopefully the regulator will enter thermal shutdown when this happens, in which case all you need to do is let it cool down and, you know, stop doing that.  But it may also just die,which is more likely if you have a clone that happens to use a crappier regulator.
But, I think these numbers are conservative.  For example, a datasheet for a Songle SRD-05VDC-SL-C relay that a lot of these modules use seems to say it will use closer 70 mA each, rather than 28 mA.  This means operating just one of these coils by itself, nevermind the rest of the Arduino, will cause nearly half a Watt to be dissipated in the regulator if you're powering from 12 V.  If you managed to turn on both coils well... nothing good.
If this is not the problem you're having, it is a problem.  You can save yourself a fair bit of trouble by powering your Nano from USB with a powered hub or reasonable quality USB-output wall adapter.  Doing so bypasses your regulator altogether.
If you're going to continue staging down 12 V to 5 V for the relay coils, then you may need an external regulator to operate the relay modules, just to unload the the Nano's regulator.  Exactly how you'd go about that depends somewhat on the construction of the relay module.  Some of them make it a bit easier on you and are design to accept voltage from a second source for the coils.


How to connect both MicroSD module and MPU9235 power in an arduino I'm really new at electronics and wiring, so please be kind. Coding is my stuff, but I'm trying to learn something here.

I'm working with a project to store the movements of a skateboard through a MPU 9235 and the idea is to save the output of the sensor to a MicroSD.

I have both components and acquired a LiPO 3.7v 400mAh to take everything off the protoboard and attach at the bottom of the skateboard.

The code is working, everything code wise is working ok, but I'm strugging to understand how to power both MicroSD module and MPU9235, since both have the VCC pin (VDD in some versions).

The current connections are replicated in Fritzing. Only replacing Arduino Uno for an Arduino Nano, and the MPU 6050 from the picture for a MPU9235.

My first thought was to connect the LiPo battery into VIN and GND pins of Nano. From there I believe that I can wire up the 3V3 output directly to VCC from MPU9235.

But what about the MicroSD module?

How would I power its VCC pin since I have no 3V3 pin left? I read that it's not right to use a digital pin as power output.

How can I connect two components that needs power from external source?

VIN takes 6-12v and it sends it through the on board regulator - so that is the best way to power the nano.

If you take a wire from the 3v3 pin and split it (solder two wires to one) then you will have two 3v3 feeds to wire to your two devices.  This will be the same as you have to do for the Gnd connections, back to the Nano.

Does that make sense? (if not I'll try and draw you something).