Trinket works with USB but not with wall adapter My Adafruit 5V Trinket works fine when powered via USB connected to my computer (and the power going in to the Trinket is 5V), but if I use a 9V wall adapter with a microUSB adapter, it just powers on but doesn't seem to actually run the program on the Trinket.

Am I over powering the Trinket and sending too much voltage to everything? If that's the case, is there some way to decrease the voltage?

Yes, you are probably over-powering the trinket. The trinket expects 5V on the USB connector. However, it has an voltage regulator on board that can take up to 16V.

The BAT pin is connected to the voltage regulator and can take anywhere from 5.5V to 16V.


Link Arduinos over 5 acre laser tag field I am building a laser tag system with an Arduino in each gun.

I want the guns to be linked during game play for many different reasons:

Start/Stop game
Nearby teammates
When a flag is captured
etc.

I don't know how to link the guns to one another during game play because the field may be large (e.g. a park). Wifi has too short of a range, cellular would cost, linking to a phone via bluetooth would drain the phone battery (and require each player have a smart phone to play).

Can you think of another way to link the guns? Radio transmitters?

Thanks!

You can use nRF24L01+

The chips offer:

Really high range with power amplifier (1km open field radius (776 acres if I'm right) , but fairly high power consumption 100-150mA @ 3.3V)
High range with PCB antenna (50-80m open field, low power consumption 14mA peak)
Low cost (0.8£-6£ a piece)
Many easy to use libraries available, possible to create a mesh network
High usable voltage range (direct Li-Po for example without step-up)


Arduino 1 can somehow support 32-bit audio? I wanted to take the audio from a device such as the PC, insert it through different ADC in arduino, processing them with DSP and DAC REnter all through to the other speakers, reading here and there on the internet but some people were put in difficulty because Arduino has a data bus to 10 bits. What problems can cause this? I can not send the same 10 bits at a time, until you arrive at 32?

First of all,what is the point of this? I'm afraid this is a XY question. You won't get that good of quality with Arduino. If you're hoping to create some sort of an amp, learn electronics and do that directly. Maybe you should just send data via serial.

Anyway, that aside, here's a chart I drew:

(Excuse my poor image alignment, PowerPoint was being a little mean today)

The bottom is all the "channels" the PC can send. The top is all the "channels" the Arduino can recieve. As you can see, there's a huge degradation in quality. Not to mention, I made this that 1 bit = 1 "channel," yet it's very much more than that.

A standard Arduino (Uno, Leonardo, etc.) has a 10 bit ADC that can read values 0-1023. The computer can output 0-4294967295! (It' exponentially grows due to permutations). You can see why I very much simplified my chart! :P

DSP won't really work well, unless you are trying to do some weird alien sounding modifications or a cheesy echo to. You probably will want to add an external 32 bit ADC. I would recommend, additionally, adding a Due or Galileo that can process 32 bit integers without emulating a bigger chip, thus greatly reducing performance and giving you a low framerate.

tl;dr: It'll work fine, but it'll have horrible sound quality. You can't send the same 10 bits until 32, since the computer changes that 32 bits into a voltage (sent to Arduino), and the Arduino translates that voltage into 10 bits.


How Arduino UNO differentiate between program/flash and serial terminal data I am excited to know how Arduino UNO or nano differentiate between program data that is to be burned into its flash when we press Upload Sketch and serial terminal data when we press Send? Is there any special sequence to identify those? How it will be identified by Bootloader?
And I have this understanding can anyone correct if I am wrong or anything you want to add will be helpful:

When we press Upload Sketch then a RST signal is sent.
ATmega controller when it receives RST signal jumps to Bootloader section of flash and waits for a perticular sequence from UART
If it receives then starts to write the data buffered from UART to flash. This process is handled by Bootloader.
If it doesn't receive the sequence waits till timeout and then jumps to flash section and starts to execute from 0x0000

Unlike out kids it does what it is told, not what we thought we told it to do.  Different instructions do different things. Serial.print("Hi"); is stored in RAM will print from Ram, however if you Serial.print(F("Hi"); it will print from flash. The "F" macro tells it where to print from. The Serial.print("Hi"); is stored in flash but moved to RAM and stored there while your program is started and is running whether you print it or not. The "F" macro keeps it in flash not using RAM. Everything that happens when it starts either in your code or the boot loader is code that has been programed and stored in the flash. The Boot loader decodes the code data stream when uploading and stores it in the specified location. It does not know what it is it just reads it and stores it. I do not know what it is called here but there use to be a program module called "CSTART" that upon reset got control; initialized all the memory and set up the variables before turning control over to the user program. Arduino does the same thing, data has to be placed in the right place before starting.


Manual TCP connection using WiFi ESP8266 module mistyped command The command is working fine if I type it directly to the serial interface

AT+CIPSTART="TCP","192.168.1.5",1647

But if I want to make it automatic and send it whenever I want from inside the code is not working at all.

Used this but it's not working (Serial1 is from the hardware sp)

Serial1.println("AT+CIPSTART="TCP","192.168.1.5",1647")

Any way to arrange the data?

You need to escape your quotes:

Serial1.println("AT+CIPSTART=\"TCP\",\"192.168.1.5\",1647");


Arduino sketch behaves differently depending on version of Arduino IDE I am assisting some friends on an Arduino Uno project, and we've noticed that when using some earlier versions of the Arduino IDE (In this case 1.0.5), the sketch behaves as desired. However, when using 1.6.5, the program behaves differently. The sketch in question is here:

https://github.com/CymaSpace/Programs---Sketches/tree/master/Tim%20Gorbunov/a3%20with%20monosetting/a3

I have noticed that when enabling verbose compilation output, the size of the compiled binary is different between the two different IDE versions. There are also some warnings in the older IDE that are not present in the newer version. There is at least one other version before 1.6.5 that is behaving the same way as 1.0.5 (it's a later version but at the moment I don't know which, I will see if I can find out and post it here later).

Any idea why the two sketches might be behaving differently and how to go about troubleshooting the problem? This occurred on both a windows and mac computer. Thanks!

There are also some warnings in the older IDE that are not present in
  the newer version.

It is a huge mistake to disregards those warnings, especially:

  warning: array subscript is above array bounds

You declared an array int useColor[2]. Its length is 2 and its indices
can be either 0 or 1. Yet you are using useColor[2], which is out of
bounds and likely to corrupt memory.

From the language point of view, this is called undefined behavior,
which means that anything can happen. In particular, it could very
well happen that the program behaves as you expect... which seems to be
the case with IDE 1.0.5. Simply changing the compiler version, or event
the compiler settings, can change the behavior.


Why does timer1 not generate correct period on CTC mode with a resolution of 5us? I have defined my code to generate an interrupt over each 5μs on CTC mode using timer1 but the output shows a time of ~15μs.

Following the equation to set the counting number to achieve the desired time

(# timer counts + 1) = (target time) / (timer resolution)

I've got OCR1A = 79 for a desired time of 5μs using no prescaler and a source clock of 16MHz on Arduino Uno.

My code is as follows:

// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define LEDPIN 9

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

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 79;

    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for no prescaler:
    TCCR1B |= _BV(CS10);

    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

void loop () {}

ISR(TIMER1_COMPA_vect)
{
  digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}

This is the output from my logic analyzer:

Is it a limitation of the Arduino or am I missing something?

My idea is to generate a PWM manually to control a servo motor using timer1 and precisely increase the period by 10μs during "on" time and get the desired angle.

After some experiments, I have discovered that my motor (MG996R) has a range from 0.6ms to 2.1ms during "on" time to move from 0 to 180 degrees.

I have tried the Arduino's Servo library but it goes far than 180 degrees (I don't know why). That's why I am building my own code for that purpose.

I got it working just analyzing time consumption of digitalWrite and digitalRead functions. They took around 13us to execute (each one), so this added up a few extra undesired microseconds to the final period.

Instead, I set up digital output using DDRD for configuring and PORTD for setting the desired output, which results in approximately 1us to set the output value (HIGH or LOW).

I changed the prescaler to 8 and the code below shows how to get a 100kHz wave output with 5us duration of "on" time using timer1 CTC mode.

void setup()
{
    DDRD = B00001000; // pin 3 as output
    PORTD &= ~_BV(PORTD3);   // set 3 as LOW

    // initialize Timer1

    cli();          // disable global interrupts

    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    OCR1A = 9;

    // turn on CTC (Clear Timer on Compare Match) mode:
    TCCR1B |= (1 << WGM12);

    // Set CS10 bit for clk/8 prescaler:
    TCCR1B |= _BV(CS11);

    // Output Compare A Match Interrupt Enable
    TIMSK1 |= (1 << OCIE1A);

    sei();          // enable global interrupts

}

ISR(TIMER1_COMPA_vect)
{
  PORTD = ~PORTD;
}


Multiple nodes with the same receiving and transmitting address I want to make a network with arduinos and nrf24l01 chips. The network will be like this:

1 master arduino
multiple (no specific number) slave nodes

I want all nodes to have the same receiving and the same transmitting address and the master arduino to understand which one send the message from the message itself.
For example:

Master:
Receiving: 0xABCDABCD71
Transmitting: 0xABCDABCD01

Slave 1
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71

Slave 2
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71

Slave 3
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71

Slave 4
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71

When master send a message, all nodes will receive it.
What I want to ask is :

Is that possible?
Will there be any problems?
Is there any other way so I can add more nodes in the future without changing the code?

as well as comment #1 the other thing will be the ack packets that the slaves will send back to the master to confirm message recieved. with all slaves sending back a ack at about the same time there will be no way for master to tell which ack is from which client, and thus who needs a retransmit. a way around this is to turn off ack for the clients and make the master transmit max times regardless. there is a rf24 fork that has broadcast mode, the makes it more easy to specify not to wait for ack before retransmitting


Library using another library I'm writing library for smart home arduino DIY project.
i want to use another library(not written by me).
here is the code:

boiler.cpp

#include "Boiler.h"

Boiler::Boiler(int pin)
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

boiler.h

#ifndef BOILER_H_
#define BOILER_H_

// include RF24 libs
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>

// SmartHome Lib Includes
#include "Device.h"
#include "TimerOne.h"
#include "timeSet.h"

class Boiler
{

    private:

        RF24 radio(7, 8);
        RF24Network network(radio);
        RF24Mesh mesh(radio, network);

        int _pin ;

        void timerIsr();
        void DrawSCR();
    public:
        .
        .
        .

        Boiler (int pin );
        void turnOn();
        void turnOff();
};

The problem is it's not compiling
the error I get is :
Boiler.h: 32:14: error: expected identifier before numeric constant
RF24 radio(7, 8)

What am i doing wrong?
Thanks,

I Have found the answer (by mistake)
i have added the includes to Boiler.cpp file

#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
.
.
.
#include "Boiler.h"

RF24 radio(7, 8);                                   // Init RF24 Radio
RF24Network network(radio);                         // Init RF24 Network
RF24Mesh mesh(radio, network);                      // Init RF24 Mesh

Boiler::Boiler(int pin ,float Rev , String Last )
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

void Boiler::init( char nodeID)
{
    _nodeID = nodeID;
    // Connect to the mesh and set Node ID
    mesh.setNodeID(_nodeID);
    if (_DEBUG) Serial.println(F("Connecting to the mesh..."));
    mesh.begin();

    // init LCD and print init data on LCD
    myGLCD.InitLCD(60);                         // Init LCD 55 contrast
    myGLCD.setFont(SmallFont);                  // Set small font
    myGLCD.clrScr();                            // clr screen
    myGLCD.print("Boiler Device",0,0);          //Print init Data on screen
    myGLCD.print("Rev :" , 0 , 10);
    myGLCD.printNumF(_rev,1 ,35,10,'.',1,'0');
    myGLCD.print(_last,0,40);
    myGLCD.update();                            // Update display

    turnOff();
}

and now it compiles ;-)


How can I pass a long as parameter and get a char array in return? I kind of new to C++, so I'm not sure how to perform such casting.

Example:

long myLong = 12345L;
convertToCharArray(myLong); //returns an array with the digits of myLong

BTW I'm working with Arduino IDE.

As with many things in C there are many ways of skinning this particular cat.

All of them rely on you first having made a character array to store the result in - you can't "return" an array from a function.

The simplest, though non-standard, way is to use ltoa(), which is an avr-libc specific function (not part of the standard libc functions):

long myLong = 12345L;
char myCharArray[10]; // Enough room for the answer + 1 NULL char

ltoa(myLong, myCharArray, 10);

The 10 in that function call defines the base to represent the number in - base 10 in this case: decimal.

Another way, which is more portable, is to format the string using snprintf():

snprintf(myCharArray, 10, "%dl", myLong);

In this case the 10 is the maximum length of string to prevent it overrunning the 10-character array we made.

A pure Arduino way of doing it would be to use the dreaded String class:

String myString = String(myLong);
myString.toCharArray(myString, 10);

Again in this example the 10 is the length of the buffer we are copying in to.

And there are more. You could do it manually, character by character using division and modulus operators, for example.


How to listen for an incoming serial string inside loop with long delay? I'm trying to build a datalogger using Arduino UNO, I'll use RS232 for the communication between PC and Arduino, the problem I'm facing now is that I'm using delay(10000) : 10 seconds as a timestep for data acquisition. however, I can't find any solution to receive a string from the serial input to Arduino while delay is executing. Here is the code :

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

void loop() {
  serialRoutine();
  dataLoggingEvery10Second(); // That's a function to receive data from the sensor and store it in SD card.
  delay(10000);
}

  // A function to handle all the serial in out
  void serialRoutine(){
  // print the string when a newline arrives:
  while(Serial.readString() == ""){
    String serstr = Serial.readString();
      /*
      *  Getters
      */
      if(serstr == "GETDATA"){
        Serial.println("Here is my data");
      }
      serstr = "";
  }
}

Any help would be highly appreciated !

void loop() {
  static unsigned long prev = 0;
  unsigned long now = millis();

  if (now - prev >= 10000L) {
    serialRoutine();
    dataLoggingEvery10Second();
    prev = now;
  }
}

This will executed at time 10s, 20s, etc. I


Strange discrete errors when reading HC-SR04 sonar sensor I'm experimenting with an HC-SR04 sonar sensor. Basically I'm measuring the distance to a cardboard box twice a second with these lines of code running on an ESP32:

unsigned long sonarMeasure() {
    digitalWrite(TRIGGER, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIGGER, LOW);
    return pulseIn(ECHO, HIGH);
}

double distance = duration * 0.03455;

The results are a bit strange. I know, that I can't expect millimeter accuracy. But why are there rather discrete jumps of about 4 mm? And when looking closer, there is another frequent jump of <1mm:

(As far as I can tell, the jumps increase at larger distances.)

Is this an issue of how I read the sensor on the ESP32, or is it something happening internally on the HC-SR04?

I'd love to understand the reason for this effect to be able to improve the accuracy of my measurements.

I think it's from the HC-SR04... it uses echos and it seems your bad readings are some kind of echo reflections.

What you should do is either remove the bad readings, or take the average/most common value of the last x readings.

Or throw away values too far off some default (like the last average) and average the rest.


Powering a 6-12V motor using a lead acid 6V battery with 6Amps of current? Hi I'm using a adafruit motor shield v2 and I need to power a DC motor 6-12V but I'm not sure if my battery will be okay for the shield. Will it burn the shield? I'm going to be using 6V so it should draw less current?

If you take the "full load" to be the "stall current", then you can work out the resistance of the winding.

R=V/I = 12/14 = 0.857Ω

From that you can then work out the stall current at 6V:

I=VR = 6×0.857 = 5.143A

That, being the stall current, is the maximum the motor will draw - the current drawn when it is trying to move an impossible amount of load and the rotor cannot move.  At that current you will melt the motor drivers (or they will go into thermal shutdown).

Of course, with a geared motor, that becomes a (comparatively) massive load and would be quite hard to achieve.  You have a 50:1 gear ratio, so the stall load is effectively 50x greater.

So there is going to be a limit to the load that you can drive with the motor before it becomes a problem for the driver.  There are ways of calculating it from the given torque, gear ratio, load/noload current ratings, etc, but I don't have all that at my fingertips right now.

So you can either "play it safe" and invest in a driver that can cope with the stall current, or experiment and measure what current is drawn by the motor with different loads and see if it stays below the 1.2A limit of the shield.


Unable to use Keyboard library with Arduino UNO even after changing the firmware So I'm trying to use my UNO as an HID device. I followed this tutorial, flashed the firmware and got the UNO to be detected as an HID device.

However, I am still getting the error

  'Keyboard' not found. Does your sketch include the line '#include '?

Here's the code -

/*
Copyright (c) 2014 NicoHood
 See the readme for credit to other people.

 Keyboard example
 Press a button to write some text to your pc.
 See official documentation for more infos
 */

// include HID library
#include <HID.h>

const int pinLed = 13;
const int pinButton = 8;

void setup() {
  pinMode(pinLed, OUTPUT);
  pinMode(pinButton, INPUT_PULLUP);

  // Starts Serial at baud 115200 otherwise HID wont work on Uno/Mega.
  // This is not needed for Leonado/(Pro)Micro but make sure to activate desired USB functions in HID.h
  Serial.begin(115200);

  // Sends a clean report to the host. This is important because
  // the 16u2 of the Uno/Mega is not turned off while programming
  // so you want to start with a clean report to avoid strange bugs after reset.
  Keyboard.begin();
}

void loop() {
  if (!digitalRead(pinButton)) {
    digitalWrite(pinLed, HIGH);

    // Same use as the official library, pretty much self explaining
    Keyboard.println("This message was sent with my Arduino.");
    Serial.println("Serial port is still working and not glitching out");

    // simple debounce
    delay(300);
    digitalWrite(pinLed, LOW);
  }
}

/*
Definitions:

 KEY_LEFT_CTRL
 KEY_LEFT_SHIFT
 KEY_LEFT_ALT
 KEY_LEFT_GUI
 KEY_RIGHT_CTRL
 KEY_RIGHT_SHIFT
 KEY_RIGHT_ALT
 KEY_RIGHT_GUI

 KEY_UP_ARROW
 KEY_DOWN_ARROW
 KEY_LEFT_ARROW
 KEY_RIGHT_ARROW
 KEY_BACKSPACE
 KEY_TAB
 KEY_RETURN
 KEY_ESC
 KEY_INSERT
 KEY_DELETE
 KEY_PAGE_UP
 KEY_PAGE_DOWN
 KEY_HOME
 KEY_END
 KEY_CAPS_LOCK
 KEY_F1
 KEY_F2
 KEY_F3
 KEY_F4
 KEY_F5
 KEY_F6
 KEY_F7
 KEY_F8
 KEY_F9
 KEY_F10
 KEY_F11
 KEY_F12

 KEY_PRINT
 KEY_SCROLL_LOCK
 KEY_PAUSE
 */

Can anyone point out what I'm doing wrong here?

If I open the rar library file, than I see a file called Keyboard.h. I'm sure you need to include Keyboard.h, than the class Keyboard is known and you can use it in your sketch.


Drawing specific RGB on touch screen I have the Arduino MEGA and an adafruit touch screen 2.8 inches.

My goal is to draw a pixel given a specific RGB

I am using the ILI9341, GFX, and TFT.h libraries to draw and control the touch screen. I noticed the drawPixel function given, in which it takes in three parameters and draws the pixel:

tft.drawPixel(4,4,ILI9341_BLUE);

But, I am trying to draw a pixel with specific a RGB. So instead, the function would ideally need 5 parameters instead of 3, x, y, and then R, G, and B:

tft.idealDrawPixel(5,6,89,234,76);

I tried putting in a number as the third parameter and not ILI9341_COLOR, and the screen just prints blue:

tft.drawPixel(45,67,255);

Is there a function that allows me to draw RGB pixels specifically? Thanks for any help!

As noted in the second paragraph on Adafruit's Graphics Library webpage,

  First thing to note is that color is 16-bit, and that includes Red, Green and Blue in a 16-bit variable. The way the color is packed in is the top 5 bits are red, the middle 6 bits are green and the bottom 5 bits are blue.

If you want to specify 8-bit color components, you could write an intermediary routine to translate from that form to the 565 form.  For example:

#define rgbDrawPixel(x,y,r,g,b) drawPixel(x,y,(((r)&0b11111000)<<8)|(((g)&0b11111100)<<3)|(((b)&0b11111000)>>3))

Note, this assumes the TFT library you're using has the same specs as Adafruit's.  That might or might not be; I don't know how to account for a 255 color number showing up as blue rather than white.


Connecting GSM Dongle to Intel Galileo-Gen 2 I have tried to connect a GSM dongle to a Intel Galileo Gen2 board and test the functionality of sending and receiving SMS through it.I know that it is easier to use a GSM shield to do above, but I'm currently doing a project in the way i mentioned above.Basically in Linux, we should know the serial port(like ttyACM0 in /dev directory) correspond to the device to communicate with it(Using AT commands).

but when i tried it in Galileo board it doesn't show such a serial port.but it detect device because lsusb command shows the device.

does anyone can help me to solve this matter?

Try updating the firmware. I'm not sure if this affects also ACM type serial ports, but the initial version of the firmware was not even creating standard /dev/ttySx, rather some weird proprietary interface.
Luckily this was fixed later on. So, in case you are still running the FW that the board came with, chances are you are having these weird serial ports.


(HELP)How to read Physical Dimensions in datasheets Sir/ Ma'am,
.
How to read the dimension labels of this IC?

I have annotated your drawing a little to help you understand it better:


RFID reader for unknown tag 125kHz I have an unknown RFID tag and tried to read its value. I bought two readers, RDM6300 125KHZ and RC522 13.56MHz. Each of the readers connected to Arduino works well with the purchased corresponding tags, but not with this tag. According to my information, the tag should be 125kHz tag, but RDM6300 foes not read it. The tag is simply not detected. I am sure that the tag works, I use it to open the door.

So my question is: Is there any other RFID reader for Arduino, which is different than the two that I have, and could work?

Thank you.

It could be something else (in the RFID low freq ~ 125khz) like a HID card.
Also it could be an NFC (high freq 13.56Mhz) that its not compatible with the RC522.

Do you have access to a phone with NFC, to start ruling out what could it be?


How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino? How to control two 12 V motors with the dual MAX 14870 Motor Drive Shield for Arduino?

I am a beginner and I need help on how to control two 12 V motors using the Pololu dual MAX 14870 Motor Drive Shield for Arduino Uno.

I had attached the screenshot for this

This picture tells you about the Arduino Connection with the with the SHIELD.

EN (Enable Pin) is used to enable and disable the motor drivers. As it is inverted SET this PIN HIGH will Disable the Motors and vice versa.
DIR pinS is used direction of rotation. It highly depends upon your connection, setting this PIN HIGH LOW will make the motor rotation from CLOCKWISE & ANTI CLOCKWISE or vice versa depends upon your hardware connection.
PWM pins are used to control the rotation speed of the MOTOR. Driving PWM signal on this pin will adjust your rotational speed. MAX PWM frequency suggested is 50Hz.
Fault is the INPUT PIN to Arduino with ACTIVE LOW signal indicating some kind of fault is there.


Assign an interrupt to any pin of the atmega328 microcontroller I need to record the appearance of a signal from the sensor on the PD0 pin. This is the first time in my life that I want to use an interrupt for this.
With your help, I configured the sketch for my pin PD0
#include <avr/interrupt.h>

volatile int value = 0;

void setup()
{
  cli();
  PCICR |= 0b00000100;    // turn on port d
  PCMSK2 |= 0b00000001;    // turn on pins PD0 (PCINT16)
  sei();

  Serial.begin(9600);
}

void loop()
{
  Serial.println(value);
}

ISR(PCINT2_vect)// Port D, PCINT16 - PCINT23
{
  value++;
}

I need to wait and take a certain action when a high signal comes from the sensor. For example, add one to the constant.
I also did not understand when interruptions occur. When the signal changes from bottom to top, when from top to bottom, or no matter how? Can't see if these settings are here? Maybe it is set somehow by default?

Here is a link to a good tutorial on how to enable, respond to, and clear interrupts on the ATMega328P device:
Arduino Pin Change Interrupts
I'll repeat the overall steps here in case this URL disappears in the future:
First, you must enable pin change interrupts:

Note the use of 3 bits in the PCICR register [0:2].  These enable pin change interrupts on ports B, C, or D in general.  You can choose any combination of these ports or all of the ports as you desire.
Next, you select which pin or pins on the enabled ports that you want to receive interrupts from.  You have control here over each individual port bit:

Then you must write an ISR (Interrupt Service Routine) to handle the interrupt once it occurs.  You have the option of up to THREE ISRs, one to handle each port or you can have a single ISR to handle any pin change interrupt.  The way this works is that when an interrupt happens on an enabled port and pin, the AVR chip calls the ISR that you have configured for that event:

So when an interrupt happens, how do you know which pin(s) caused the ISR?  Let's assume you used a single ISR to handle all 3 ports.  At this point you know only that an interrupt happened somewhere.  That's the purpose of the PCIFR register bits.  From the AVR datasheet we see this:

By checking the status of these bits you can now tell which pin or pins caused the interrupt.  Note that there CAN BE MORE THAN ONE, so it's up to you to decide the priority of each one and handle them accordingly.  Note that you only get ONE chance to read these during any ISR function call since they get cleared when the ISR executes.
One last note.  You MUST call the sei(); function to enable any interrupt to the CPU before any interrupt will happen.
In your example, however, you seem to be attempting to generate a pin change interrupt on an output. This is probably NOT what you want.  Try simply using the existing LED output pin as an indicator and choose a different pin, setup as INPUT, to be your pin change interrupt source.


Arduino Pro Micro not recognised by computer or showing up in ports Around 4 days ago my Arduino Pro Micro arrived. I've been messing around with it, using it to run keyboard commands on a computer. Just recently, whenever I plug it in to the computer it isn't detected by ports or anything. The green light is still on, and the left red light (looking at it from the side of the micro USB input) still works as well, however the right red light no longer works. Can someone tell me what's happening? Have I broken it all ready?

The arduino pro micro is notoriously difficult to program. I am sure you have figured this out when first installing the drivers but on power up, the micro runs a bootloader for <750ms  so for me at least, it was extremely difficult to install drivers.
However, if you look at this guide by sparkfun, you will see that resetting the board in quick succession will load a longer 8 sec bootloader, which gives your more time to program it. Obviously, this is not normally something you need to worry about as the Arduino IDE automatically resets the board sending it into the bootloader when you upload a sketch to it.
Back to your problem, if it is not popping up as a device when you plug it in to your computer, go into control panel > system > hardware > device manager and look to see if you can find it there. If it still doesn't show up, do what I said above and reset it twice and hopefully you will see the bootloader appear where you can reinstall the drivers for it. You can find the appropriate drivers in the same location where you installed the IDE originally.
Hope this helps!


Arduino Due - creating an 8Mhz clock signal I am attempting to interface a OV7670 camera to an arduino Due. (I am fairly new to this although have been programming for many years).

I need to generate a clock signal for the camera at a minimum of 8Mhz - I realise using the pre-scalers I can only get an approximation but I am cool with that.

I finally got a nice steady 3mhz signal from the sketch below (note that the irq routine for TC6 is not used and will be removed very soon (as soon as I get home).

I think I have a conceptial problem with the timers because as I am initialising RA and RC to 1 and telling via TC_Configure to toggle the line, and because I am using CLOCK1 (42 Mhz), I believe with those values of RA and RC I should be getting a 21'ish MHZ signal.

Ie RA starts at zero. First CLOCK1 tick. (at second/48,000,000) interval. RA Goes to 1 COmpares to RC Because they are equal, resets RA to 0 and toggles TIOA6 Next Clock1 tick occurs.....

As I said I am only getting a 3Mhz signal.

void TC6_Handler()
{
        TC_GetStatus(TC2, 0);

}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
        pmc_set_writeprotect(false);
        pmc_enable_periph_clk((uint32_t)irq);

        TC_Configure(tc, channel,
               TC_CMR_WAVE |
               TC_CMR_WAVSEL_UP_RC |
               TC_CMR_TCCLKS_TIMER_CLOCK1|
               TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

        TC_SetRA(tc, channel, 1); //50% high, 50% low
        TC_SetRC(tc, channel, 1);

        PIO_Configure(PIOC,
                   PIO_PERIPH_B,
                   PIO_PC25B_TIOA6,
                   PIO_DEFAULT);

       TC_Start(tc, channel);

}

void setup(){

        startTimer(TC2, 0, TC6_IRQn);
}

void loop(){
}

the code below should give you a 8.4MHz signal on digital pin 7 of the due. I have used it to generate a 4.2MHz clock (by setting REG_PWM_CPRD6 = 20; and REG_PWM_CDTY6 = 10; but I think it should work for a 8.4MHz clock also.

I have been using this to provide a 4.2MHz clock signal instead of using a crystal oscillator for an ADE7913 and can confirm it is working well in that application. I have taken this from the arduino forum here.

#include <Arduino.h>

const unsigned long serialPeriodMillis = 2000;
unsigned long previousMillis = 0;

void setup()
{
  int32_t mask_PWM_pin = digitalPinToBitMask(7);
  REG_PMC_PCER1 = 1 << 4;                         // activate clock for PWM controller
  REG_PIOC_PDR |= mask_PWM_pin;                   // activate peripheral functions for pin (disables all PIO functionality)
  REG_PIOC_ABSR |= mask_PWM_pin;                  // choose peripheral option B
  REG_PWM_CLK = 0;                                // choose clock rate, 0 -> full MCLK as reference 84MHz
  REG_PWM_CMR6 = 0 << 9;                          // select clock and polarity for PWM channel (pin7) -> (CPOL = 0)
  REG_PWM_CPRD6 = 10;                             // initialize PWM period -> T = value/84MHz (value: up to 16bit), value=10 -> 8.4MHz
  REG_PWM_CDTY6 = 5;                              // initialize duty cycle, REG_PWM_CPRD6 / value = duty cycle, for 10/5 = 50%
  REG_PWM_ENA = 1 << 6;                           // enable PWM on PWM channel (pin 7 = PWML6)

  Serial.begin(115200);
  Serial.println("Serial on");
}

void loop()
{
  if (millis() - previousMillis > serialPeriodMillis) {
    Serial.println("TIC");
    previousMillis = millis();
  }
}


Reading Json object name in arduino How do I read the Json object name in arduino? For { "pi" : "3.14" }, I want the arduino to automatically read the object name "pi" and then th value "3.14"
I'm using arduino Uno.

There is a brilliant JSON library called ArduinoJSON. It can be installed using the arduino library manager.

See https://bblanchon.github.io/ArduinoJson/doc/decoding/ for further details.

To loop through the keys, you can use:
https://bblanchon.github.io/ArduinoJson/api/jsonobject/begin_end/

or if you know the key, you can do jsonObject["pi"] to get the value


Measure square wave frequency I'm working with the Arduino Due ans I used the following code:

// period of pulse accumulation and serial output, milliseconds
#define MainPeriod 100
long previousMillis = 0; // will store last time of the cycle end
volatile unsigned long duration=0; // accumulates pulse width
volatile unsigned int pulsecount=0;
volatile unsigned long previousMicros=0;

void setup()
{
  Serial.begin(19200);
  attachInterrupt(6, myinthandler, RISING);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= MainPeriod)
  {
    previousMillis = currentMillis;
    // need to bufferize to avoid glitches
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; // clear counters
    pulsecount = 0;
    float Freq = 1e6 / float(_duration);
    Freq *= _pulsecount; // calculate F
    // output time and frequency data to RS232
    Serial.print(currentMillis);
    Serial.print(" "); // separator!
    Serial.print(Freq);
    Serial.print(" ");
    Serial.print(_pulsecount);
    Serial.print(" ");
    Serial.println(_duration);
  }
}

void myinthandler() // interrupt handler
{
  unsigned long currentMicros = micros();
  duration += currentMicros - previousMicros;
  previousMicros = currentMicros;
  pulsecount++;
}

to measure the frequency.

I can measure frequencies higher than 1.5kHz accurately, but I can't seem to measure lower frequencies.

How can I measure lower frequencies, say 400Hz and above?

Thanks.

It seems you have a problem of concurrent access to duration and pulsecount variables which are inter-related; with your code, it is possible that (and I guarantee that it will):

loop() reads duration value (in line unsigned long _duration = _duration;) but gets interrupted before executing the next line
myinthandler() changes both duration and pulsecount (it cannot be interrupted as it is already triggered by an interrupt)
loop() proceeds to where it was interrupted (after myinthandler() returns) and executes line unsigned long _pulsecount = pulsecount;: the values in _duration and _pulsecount do not match anymore!

To protect the access to pulsecount and duration variables, you have to disable interrupts inside loop() just for the time you get their values:

void loop() {
    ...
    // Disable interrupts while we get and reset duration and pulsecount
    cli();
    unsigned long _duration = duration;
    unsigned long _pulsecount = pulsecount;
    duration = 0; // clear counters
    pulsecount = 0;
    // Now we can re-enable interrupts again
    sei();
    ...
}


Elegoo Nano timer prescaler problem I am trying to use Timer2 on an Elegoo Nano to produce a "tick" interrupt every 10uS. My plan was to set Timer2 to CTC mode with a /8 prescaler (to get a timer clock of 2MHz from the 16MHz chip clock) and a compare value of 19 (to reset the timer every 20 counts) which should trigger the compareA ISR at 100KHz (every 10us). The problem is that only prescale values of 64 or greater work as expected. Setting the prescaler  to any value lower than 64 actually results in the "tick" interval getting much longer (10 times the interval or more). I have carefully studied the ATmega628 datasheet to see if I am configuring every register correctly, but I don't see anything wrong with what I am doing. Here is my code...

void initTimer() {

    // ---Disable interrupts during timer initialization
    cli();

    // ---Counter compare value (make CTC interrupt fire every 10uS)
    OCR2A = 19;

    // ---Clear TCCR A register (not used)
    TCCR2A = 0;

    // ---Enable CTC mode with divide-by-8 prescaler
    TCCR2B = _BV( WGM22 ) | _BV( CS21 );

    // ---Enable Timer2 CTC interrupts for compare A match
    TIMSK2 |= _BV( OCIE2A );

    // ---Initialize timer 2 to zero (not really needed in my situation)
    TCNT2 = 0;

    // ---Turn interrupts back on
   sei();
}

SIGNAL( TIMER2_COMPA_vect ) {

    /*
    ** This should execute every 10uS, but for prescaler values
    ** below 64 the interval is many times longer than expected.
    */
}

Can anyone point out my mistake?

Can anyone point out my mistake?

Your mistake is in thinking that it's possible to do more than you can within a 10uS period.

At 16MHz each instruction takes 63ns (for single-clock instructions). 10nS gives you a maximum of (10,000 / 63) 156 assembly instructions.  Into that you have to fit the preamble and postamble to store the registers to the stack and retrieve them again.

The remaining clock cycles (maybe no more than 100) won't give you much time to do complex things. And given that many of the Arduino API calls are quite heavyweight, even just something as "simple" as a digitalWrite() can overflow that many times over.


externally powering the Arduino questions I have several questions on externally powering the Arduino Uno

I have a 7.2V power source that is 6 rechargeable AA batteries together, 1.2V and 1300mA each. If i use a 4.70 and 1.5 ohm resistors together to give 1.16 amps, can I power the arduino with this?

Can I power a servo off the Arduino 5V rail If i place a 470uF or more capacitor alongside it?
Will anything heat or blow up or am I just being paranoid like always?

I am guessing that you are thinking of dividing down the battery voltage from 7.2V down to 7.2*(4.7)/(4.7+1.5) = 5.5V. This is generally a bad idea for a few reasons.

The battery voltage will not be a constant 7.2V. When they are fully charged it could be even higher. As they discharge they could drop significantly and your Arduino POR (power-on-reset) circuit would potentially shut the board down before the batteries are fully discharged
The batterys' internal resistance would probably drop the output voltage considerably once the resistors try to draw 1A of current. It might even collapse the voltage to some unusable value.
Even if the battery internal resistance is very low and even if the Arduino is not drawing much power (or even off) you will always be drawing ~1A of current from the batteries. This will rapidly drain your batteries and will also heat them up from their internal resistance. Not to mention your external resistors better be able to handle > 5W or so. Conclusion: lots of unnecessary heat and power loss.

To answer your other question, assuming the servo is low power and the Arduino power supply is up, you could power it from the Arduino 5V supply (not your batteries).

If you need to use batteries to power an Arduino, I would highly recommend a power regulator to produce a stable output voltage to power your Arduino.


Servo limitations vs SoftwareServo I heard that Servo library cannot send and receive from other arduinos without inturrupting the timer and messing up the motors. SoftwareServo is supposedly the answer to this. Is this true? Neither libraries are working for this problem at the moment.

I'm not sure which SoftwareServo library you are talking about, but with regards to the built in "Servo.h", no, it will not disrupt the arduino's other communication abilities, and they will not disrupt it.

I've used servos simultaneously with Serial, I2C, and SPI before and never had any problems.

The servo library does use a timer, but it will only conflict with an external library or code that uses the same timer. Which timer it uses depends on the board, just look in libraries/Servo/src/avr/ServoTimers.h to see which it uses, in what order as they fill up. Filling one up takes effort though, by default it puts up to 12 servos on each timer. The processing overhead is very low since they only update at 50Hz, so that will not become a problem.


AT command XBee from atmega to disable DIO5 (associated led) I community! I need put ATcommand to my XBee from my atmega using a "xbee library" and a function that I have found in internet. I think the ATComand is "ATD50" to change the DIO5 to value "0" (disabled). My intention is to turn off a led connected into DIO5 (digital input/output 5 (associated led)) after X second/minutes of turning on the device (so that it doesn't turn one again after initial check).

This is a part of my code:

#include <XBee.h>
XBee xbee = XBee();
uint8_t atdCmd[] = {'A','T','D','5','0'}; //<---command to put DIO5 to "0" (disabled)
AtCommandRequest atRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();
void setup()
{
delay(30000);
atRequest.setCommand(atdCmd);
xbee.send(atRequest);
}
void loop()
{}

...but it doesn't work!
Thanks guys!

finally I solved the problem with this code:

uint8_t atdCmd[]={'D','5'};
uint8_t value[]={4};///pongo DIO5 a output LOW
uint8_t length=1;
AtCommandRequest atRequest = AtCommandRequest(atdCmd, value, length);
xbee.send(atRequest);

The problem was that I tried to put command with 5 caracters,... and only accepts 2 caracters for "AT command"


Send AT commands to ESP8266 from Arduino Nano serial monitor I have an Arduino nano and an ESP8266-01.

The first thing to do seems to be to send AT commands via the serial monitor and see the replies.

ESP connect as follows:

  GND   GND
  GPIO2 not connected
  GPIO0 not connected
  RX    to Arduino RX via level shifter
  TX    to Arduino TX via level shifter
  CHPD  3.3V
  RST   3.3V
  VCC   3.3V

Image of breadboard (imgur rejects)
https://www.dropbox.com/s/aif8afi29amy02h/20180807_135218.jpg?dl=0

When connecting the red light comes on and the blue light flashes quickly (and the Arduino RX light flashes with it) then goes out.

Here is the sketch I'm using. (The ESP8266 must be disconnected from RX+TX for uploading of the sketch to work.)

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

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(250);
  digitalWrite(LED_BUILTIN, LOW);
  delay(3000);
 }

(I like to blink the LED to demonstrate that uploading worked.)

With the serial monitor set to 115200 (NL&CR) I sent AT and nothing happens.

What have I got wrong? I really don't understand! Thanks in advance for any suggestions.

(This is actually my third ESP8266. The first worked fine on 5V but stopped working after I set the baud rate to 9600. I presume 5V killed it but it's strange that it worked for so long. The second, connected as above, when powered up made that power supply red hot and melted the jumpers.)

First problem is that io 0 of the esp8266 must be pulled HIGH for normal boot. With io 0 not HIGH, the esp8266 starts in flashing mode.

Your other problem is the reset pin connection. It must be connected with pull-up resistor or not connected.

See ESP8266 Hardware Design Guidelines

  Pin32 serves as an RST pin which can be left floating when it is not
  used. The reset pin is held low when the chip is enabled. In order to
  avoid resets caused by external interference, the lead is generally
  required to be short, and no external pull-up resistor is necessary

I suspect that "The reset pin is held low when the chip is enabled." is a bad translation. They say in pin description "32 EXT_RSTB I External reset signal (Low voltage level: Active)". What they mean is that the chip resets when reset pin is set LOW.


Updating mysql data using SIM900 and Arduino Thanks in advance for your kind support.
I am not an expert but have little understanding of concepts and trying to integrate various things to get some useful projects for my purpose. I want to update the database (MySQL) on shared hosting using the SIM900A module and Arduino nano board. With help of examples shared on this platform and my understanding, I achieved a significant part of the same.  The following is the approach I have adopted and the current status:
I have put a PHP code on the server (shared hosting) to update the database once it received the GET request
I have also uploaded the code in the Arduino with proper connections for sending requests to the server.
Problems I am facing:
I am not able to update the data on my specific database, through the Arduino sent request. the same code is working with Thingspeak, My code is also working otherwise, as I have tested through web form request and URL request. I am not sure where is the problem.  I am also not getting any errors. The response to the AT request is "OK" only
Though I can update the Thingspeak channel, only till the command lesser than 61 characters, which are sent after the AT+CIPSEND command. There is no error, even if the request size increases, but data updated only till 61 characters (including \x1A character)
"I am wondering, is this the limit, that cannot be increased or there is some possibility to increase it."
I understand that the problem appears to be in approach and not in code, as the code is working in itself. However, please let me know, which code I need to share, as it is a multifile code on the web-editor

I have faced a similar issue. It happened due to an SSL issue. You can find all info about it here - https://stackoverflow.com/questions/62950561/sim800l-gsm-module-working-with-http-and-shows-error-with-https-why


ESP8266 & Initial State Has anyone been successful in connecting an ESP8266 to the Initial State IoT platform?

On the platform there is only one example with Cactus ESP. I tried it but it did not work because I have a NodeMCU.

Can you please share your Arduino code?

If you use the Arduino IDE Board Manager to install the support for ESP boards
an ESP8266 can be programmed in EXACTLY the same way as you program an Arduino.

This mean you will now be able to follow the Cactus Micro sample up to the point where you upload CMTempTest.ino.

The problem with the HubTest.ino code is that relies on having a serial link between the Cactus board's main processor and its ESP8266 network slave processor.  You don't have that so all the AT commands are not going to work.

However you do have a number of examples that come with the ESP addition to the IDE and in there will be a network client example.  You need to look at how that code forms a connection and make HubTest.ino work in that way.  I can't tell you exactly what to do (I don't know) but any lines that are AT related need to be replaced by "proper" networking code.


Controlling a Stepper Motor - sending to specific positions on a 'buttonPushCounter ==' cue, forwards and backwards I am working on a project using an Arduino control a Stepper Motor. The motor drives a lead screw which moves coloured filters to specific positions along a linear track - forwards and backwards.
The movements are triggered by another device that counts its revolutions (using a sensor. The Arduino reads the inputs and activates the motor on specific revs ie. at 10 move 70mm forwards, at 30 move 70mm backwards.
I can control the Stepper to execute precise moves repeatedly one after another, independently of the counter. I can link the Arduino to the counter and switch on/off an LED at specified counts. But when I try to run the motors from the counter, it's triggered but only moves in tiny discontinuous steps, and only goes one way. Here is that Sketch below. Any help very welcome. Thanks.

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

  if (buttonPushCounter == 10) {
    digitalWrite(ledPin, HIGH);
    Astepper1.moveTo(600);
    Astepper1.setSpeed(600);
    Astepper1.run();
  }

  if (buttonPushCounter == 30) {
    digitalWrite(ledPin, LOW);
    Astepper1.moveTo(200);
    Astepper1.setSpeed(600);
    Astepper1.run();
  }

  }
}

Thanks. Your description of the fault makes sense to me. As you point out blocking would be a problem as I need the counter to continue to be registering while the movement is being executed. I've revised the script as you suggest - inside the loop but outside the if statement - have I done as you meant? But the same problem occurs - the motor advances in single steps.

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // save the current state as the last state, for next time through the loop
    lastButtonState = buttonState;

    if (buttonPushCounter == 10 ) {
      digitalWrite(ledPin, HIGH);
      Astepper1.moveTo(20000);
      Astepper1.setAcceleration(6000.0);
      Astepper1.setSpeed(600);
      //Astepper1.setSpeed(600);
      Astepper1.run();
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

    if (buttonPushCounter == 30) {
      digitalWrite(ledPin, LOW);
      Astepper1.moveTo(200);
      Astepper1.setSpeed(600);
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

  }


Adafruit CC3000 Wifi Shield on IRQ 2? I'm using an AdaFruit CC3000 Wifi shield as an HTTP server with an Arduino Uno.

I have a script which works fine -- logs into my Wifi and listens for connections as it should.

However, I want to use an infrared library which writes to the CC33000 default IRQ 3, so to avoid conflict I change the following setting:

#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!

to the only other Interrupt pin

#define ADAFRUIT_CC3000_IRQ   2  // MUST be an interrupt pin!

The device hangs at "Initializing" .. or at least I see neither of the subsequent lines in the following code on my serial monitor:

Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  Serial.print(F("\nAttempting to connect to ")); Serial.println(WLAN_SSID);
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

I've stripped everything back down to just the example code for HTTPServer to ensure it's not a conflict with my own code or the IR Library. I've changed the setting from 2 to 0 and 1 thinking there was some confusion over literal IRQs vs Pins, but those settings generate the "Couldn't begin" error trap.

Is there any other setting that I need to vary in order to get the CC3000 to opearate on IRQ 2 or is this a hardware bug and I'm out of luck if I want to use Pin 3?

It is a "hardware bug" as you so aptly put it. As far as I know, the only way to get the CC3000 board to use pin 2 as the IRQ is to physically rewire the connections. I did exactly that on my board and it works without a problem, leaving pin 3 free to use for whatever else you want. You can see what I did here.
It basically involves cutting the trace wire and running a jumper cable between the holes next to the pins.

The important thing to understand perhaps is that pins 2 and 3 are available to use for IRQ on the Mega and Uno, but it is an actual dedicated pin on the CC3000, hence why you have to go to this effort to change it. Also remember that once you have cut the trace to pin 3 it becomes an open/free pin and is no longer connected to the wifi shield. By the sounds of your requirements this shouldn't matter, but it is still useful to know.

If you haven't already, I recommend that you read the documentation for the CC3000 board, as it really helped me understand the irritating intricacies.

But yeah, if you choose to follow this and reroute the pin, it works perfectly. Hope this helps, even if it is a bit late.


Connecting 4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino I am trying to make an obstacle avoiding robot with robotic arm. First, I am from software programming field with no experience in electronics, circuits and Arduino. Using online tutorials so far I am able to blink an led, bluetooth communication between PC and Arduino and sonar range measurement.

After doing a lot of research on internet I have made the following diagram to connect  4 servos, 2 motors, hc-05, sr-04 and L293D to Arduino using "fritzing" software. I have the sketches for running servos and motors but I am not sure the circuit is correct due to the lack of knowledge in electronics. My doubts are,

1) Is 6V supply enough for 4 servos and 2 dc to work?

2) Is the connection between L293D and 2 DC motors correct?

The final robot will look like (I hope!) a "mearm" like robot arm attached on top of an obstacle avoiding robot.

UPDATED:

1) Is 6V supply enough for 4 servos and 2 dc to work?

If the motors are 6V motors then 6V is not only enough, it is what you need. What you should be asking is "Can my power source provide enough current.

  2) Is the connection between L293D and 2 DC motors correct?

Not quite. You have only got half your grounds connected up. Also 3,4EN should be connected to Vcc1 not Vcc2.

1A/2A and 3A/4A are the direction/break pins (one high and one low for a direction, both low for break). The EN pins can be (if you wish) used to control the speed with PWM (if you have any spare) - if not then they should be tied to the logic supply voltage, Vcc1, not the power supply voltage, Vcc2, since that can be up to 36V and is way too high for logic inputs like EN.


Avrdude fails to verify after upload I'm using the most recent Arduino IDE to upload a sketch to an Arduino Uno, and the upload seems to succeed, but the final verification step fails with the error:

avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x1e950f
avrdude: reading input file ".build_ano/uno/firmware.hex"
avrdude: writing flash (30908 bytes):

Writing | ################################################## | 100% 5.01s

avrdude: 30908 bytes of flash written
avrdude: verifying flash memory against .build_ano/uno/firmware.hex:
avrdude: load data flash data from input file .build_ano/uno/firmware.hex:
avrdude: input file .build_ano/uno/firmware.hex contains 30908 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 3.96s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x7800
         0xff != 0xfe
avrdude: verification error; content mismatch

avrdude: safemode: Fuses OK (H:00, E:00, L:00)

avrdude done.  Thank you.

I've re-ran the upload several times, and tried different USB cables, but I get the exact same verification error each time. Does this mean the upload effectively failed (presumably because the flash memory has gone bad), and that my sketch is not running on the Arduino? Is there any way I can fix this?

I tried uploading to a different Arduino Uno, and I received the exact same error.

So here is my official answer ;-)

Your sketch goes above the 30k flash available on the Arduino Uno.

Yes the Uno has 32k of flash, but 2k is used for the Arduino bootloader. if you convert 0x7800 in decimal that gives you 30720 which is exactly 30k. And your sketch is 30908 bytes so it's 188 bytes too long.

Try optimizing it.

A second alternative would be to use the Optiboot bootloader replacement (https://github.com/Optiboot/optiboot) which only uses 512 bytes.


serial write pixels of a bmp image I'm looking for a way to read a 24 bpp bmp file from a SD cart, and than convert it to text and write it to the serial monitor.

So the output should look something like this:
R255,B255,G255

And that for each pixel

To read the pixels, start with this:

int32_t readNbytesInt(File *p_file, int position, byte nBytes)
{
    if (nBytes > 4)
        return 0;

    p_file->seek(position);

    int32_t weight = 1;
    int32_t result = 0;
    for (; nBytes; nBytes--)
    {
        result += weight * p_file->read();
        weight <<= 8;
    }
    return result
}

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

    Serial.print("Initializing SD card...");
    if (!SD.begin(53)) {
        Serial.println("initialization failed!");
        while (1); // <- this is how you should block execution, not with returns
    }
    Serial.println("initialization done.");

    // Open
    bmpImage = SD.open("Circle.bmp", FILE_READ);
    textFile = SD.open("test.txt", FILE_WRITE);

    int32_t dataStartingOffset = readNbytesInt(&bmpImage, 0x0A, 4);

    // Change their types to int32_t (4byte)
    int32_t width = readNbytesInt(&bmpImage, 0x12, 4);
    int32_t height = readNbytesInt(&bmpImage, 0x16, 4);
    Serial.println(width);
    Serial.println(height);

    int16_t pixelsize = readNbytesInt(&bmpImage, 0x1C, 2);

    if (pixelsize != 24)
    {
        Serial.println("Image is not 24 bpp");
        while (1);
    }

    bmpImage.seek(dataStartingOffset);//skip bitmap header

    // 24bpp means you have three bytes per pixel, usually B G R

    byte R, G, B;

    for(int32_t i = 0; i < height; i ++) {
        for (int32_t j = 0; j < width; j ++) {
            B = bmpImage.read();
            G = bmpImage.read();
            R = bmpImage.read();
            textFile.print("R");
            textFile.print(R);
            textFile.print("G");
            textFile.print(G);
            textFile.print("B");
            textFile.print(B);
            textFile.print(" ");
        }
        textFile.print("\n");
    }

    bmpImage.close();
    textFile.close();

    Serial.println("done write");
}`

Source: Arduino StackExchange Question: How to read bitmap image on arduino

The text output of this should be a file with an array of strings like R10G100B25, where R is the red component of the pixel, G is the green component and B the blue one. Work out how to print these to the serial output.

Note this is only compatible with the 24bpp format.


Arduino Uno not Detecting on Laptop I have an Arduino Uno. The story is I installed Arduino IDE and Drivers before even buying an Arduino Board. I used it a little and when I bought and connected an arduino board, I was unable to make it detect. I smacked a little usimg google and was able to somehow Fix this. but again another day, It worked a little and started creatimg problems. now its not detecting. Please suggest me a way To make it work...
Should I format my windows 7 and Reinstall all the drivers as per rules?

under the IDE make sure you have set the correct board and comm port. go to tools>>board then choose your board then tools>>Comm to choose the correct comm port.

is the IDE saying anything about having problems connecting to the board?

and no re-installing all drivers should not be necessary.


Moving an object in an area I am planning to build a little game and I would need to move a small magnet inside a rectangular area. Ideally I would be able to control movement arbitrarily e.g. using a joystick.
I am trying to find a way of doing this, something like an actuator, I guess, but allowing movement in 2D.
Any suggestions on which parts to use?

Edit : in brief, what I'm trying to do is this. I have a piece of plywood, underneath which I want to put a magnet. The magnet will be moveable using a joystick (everything controlled through an Arduino) and will be used to move a magnetised figurine on the other side of the plywood. I guess in term of precision of movement I am not looking for extreme precision, having something accurate to 2-3mm would be absolutely fine. Haven't really thought of speed... But not looking for extreme high speeds.

First you need to think about your axes configuration, then about the actual implementation. I for example can directly think of 2 options:

You could arrange your axes perpendicular to each other, like a Cartesian coordinate system. Here you might need more parts to build it, than with other arrangements, though it is a sturdy system and the positions and paths are easily to calculate. For implementation there are 2 common ways, both using stepper motors in most cases:

You could let the magnet travel on the 2 perpendicular axes pulled by a belt and stepper motor for each axis. As you have to mount one axes onto the other, you might need to use 2 stepper motors (one for each side) for the first axis (depending on your dimensions, how smooth the axes glide and how much force is introduced by dragging the figurine). This approach is mostly used by 3D Printers, since they need rather fast movement, which is also rather precise, but don't need to accommodate high forces.
Instead of belts and pulleys you could use threaded rods for each axis. The magnet is mounted on nuts on these rods. Rotating the rots will move the magnet over the axis, since the magnet is fixed in it's orientation. The precision is highly dependent on the used rods, but all in all it is often more precise, than belts. But it is also way slower.

You could use only rotational axes, like a SCARA robot. It has a rod on a rotational axis and another axis at the end of it. This approach might use less parts, than the Cartesian approach, but you need good servos to have precise and jitter-free positioning (though you could also go for a geared stepper motor here). Also the arm of the robot can look out under the field quite a bit, when positioning it to the far one side.

All of the above approaches can be way more precise, than you need it. They are all viable options.

I personally would go the first way, Cartesian axes with belts and pulleys. The principle is straight forward and you can easily hide it under your piece of plywood (including a margin for all the mechanical stuff of course).


send and recieve analog data from one arduino to another arduino via web/ethernet i am able to send audio signal through mic and send it via arduino and receive it on speaker.
i need two things
1.) The voice i am hearing on speaker has on speaker has lots of noise with it. i need to reduce it
2.) I need to send that analog signal received  from the mic via Ethernet/web to another arduino. i have Ethernet shield i am able data from switch but not from mic.
let me start from the beginning, i have attached mic to the audio amplifier and have attached output of the amplifier to the a0 pin of the arduino. The arduino is connected to the DAC(PCF8519) with a5 and a4 pin of the aurdino. The output of the dac is connected to the LM386 audio amplifier module and its output is connected speaker. when i speak via mic i am able to hear it on speaker but it has has some noise attached to it. IF you can suggest solution for that it will be great.
now i want to send the data of the mic to another arduino via web/Ethernet. i am able to get the data of the switch but not been able to get proper data from the mic.So pls help out with that.
here is my audio amplifier circuit:

here is my code for one arduino code that worked
`#include "Wire.h"`
 #define PCF8591 (0x90 >> 1)
 void setup()
  {
    Wire.begin();
    pinMode(0,INPUT);
   }
 void loop()
   {
     Wire.beginTransmission(PCF8591);
     Wire.write(0x40);
     Wire.write(analogRead(0));
     Wire.endTransmission();
   }

I need to reduce the noise on the speaker and i want to send the data of the mic via web/Ethernet to another arduino.

ADC input has 100Mohm impedance. By placing C4 the signal at the ADC input has no DC path, is just floating between -0.7v and 5.7v , limited only by the input clamping diodes.
ADC can convert only voltages between 0 and the voltage reference, I suppose you use the default 5V reference.
But your signal is floating, and the ADC will cut any peaks outside of the conversion area giving the noise you hear.
Another issue I see here is that the data sheet of LM386 specifies a load between 4ohm and 32ohm. There is no warrantee that it will work without a load as in your case. Most likely not.
So you might want to connect C4 to a proper load and take the signal for ADC straight from pin 5 of LM386 which is auto balanced at half of the voltage supply.

simulate this circuit – Schematic created using CircuitLab
Later edit after I found the source of the schematic, there are also comments there that the schematic will never work with Arduino with the capacitor connected, the only working application was a sound detector where the signal distortion does not matter.
Please do not trust the content of any unknown website published by an anonymous just because it looks like a tutorial made by somebody who knows something.
Edit to add some info on how to debug the issue.
First, in the above schematic replace the resistor with a speaker and see if the sound is good. If not than see what is wrong with your amplifier.
If it's good and loud without any distortion then put the resistor back.
Use a binary mode serial monitor like Realterm to see how your data looks, the Arduino serial monitor works only in Ascii mode which turns a byte into three ascii chars which is slow.
Something like that
void setup() {
    Serial.begin(230400); // opens serial port, sets data rate to or maximum supported by your board to minimize latency
}

void loop()
   {
     unsigned int temp;
     temp = analogRead(0);
     temp = temp>>4; //strip low bits to fit in a single byte
     Serial.write(temp);
   }

Then see how your data looks, if you have to many 00 or to many FF than you know that your data us upper or lower limited or what is wrong with your signal.
I hope you are aware that the ADC conversion takes 100us and the wire transmission also around 200us the maximum sample rate you can expect is around 3khz and a maximum bandwidth of the audio signal of 1.5kHz which is half of the telephony bandwidth, you might want to use a faster DAC and use some non blocking ADC reading to use the time while ADC is working like in this article


Arduino MKR GSM 1400 fails to start up without Serial Monitor This question is similar to another question, but I have added more details. See: MKR GSM 1400 Works only when connected to computer.
I have designed and built a custom board into which I plug an Arduino MKR GSM 1400. It's a basic IO abstraction level shifter as the system I am integrating to run on 24V logic (done via opto-couplers). Everything is working perfectly and as-designed. I've added an I2C EEPROM.
When I boot the board from an external ATX supply +12V line it doesn't complete setup. After I've left it for some time, I connect it to my PC USB port and open the serial monitor in the Arduino IDE and it simply completes the setup process and enters loop successfully.
Voltages are perfect. The 12-24V supply is first fed through a standard 7810 (since I need +10V for the analog lines of the controlled system) and then a 7805. The +5V output of the 7805 is sent into the Vin of the Arduino. Measuring VIN with a DMM reads +5.07V and VCC reads +3.33V. I have a 3.7V 300mAh 25C Li-Po connected to the battery port on the Arduino, to deal with the current requirements as specified in the documentation.
I thought this could be a power issue, so I also tried booting it with a 10Ah USB Power bank that has 2 x 5V 2A (3A Max) USB ports. Same result, until I connect the PC with the serial monitor.
Simplified Arduino Code:

#include <MKRGSM.h>
#include <Wire.h>

GSM gsm;
GPRS gprs;
GSMServer server(80);
GSMSSLClient client;
GSM_SMS sms;

void setup() {
  //Initialise Serial
  Serial.begin(9600);
  while(!Serial)
  {}
  Serial.println("Gineer.Industrial.GSM.Controller");
  Serial.println("www.gineer.co.za");
  Serial.print("Hardware Version: ");
  Serial.println(hwVersion);
  Serial.print("Software Version: ");
  Serial.println(swVersion);
  Serial.println();

  Serial.print("Connecting");

  bool connected = false;

  while (!connected) {

>>> Here is where it gets stuck until I plug in the USB Serial Monitor, and then it continues happily

    if ((gsm.begin(SIMpinNumber) == GSM_READY) &&
        (gprs.attachGPRS(SIMgprsAPN, SIMgprsLogin, SIMgprsPassword) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.print(".");
      delay(1000);
    }
  }
.
.
.

Interestingly, the +5V output pin on the Arduino measures 4.68V when not connected to the PC. I don't however use this pin as I have the 7805 on my board. All other voltages measure as above at all times.

while(!Serial) {} will wait for a serial connection and in your program will block execution until it gets one.
Remove it and your program should continue without the serial monitor.


Issues converting an uint32_t into a char* I'm using a capacitive touch sensor that as 12 touch points and stores it's state data as a binary number.

I want to take that state, add a bit of data onto the front, and then send it up to a server via websockets. I'm using the Arduino Websockets library for my websocket client.
The library has a sendBinary method that allows you to provide a character pointer for the data.

So, I wrote a function that makes a new 32 bit unsigned integer, adds my metadata, then the touch state, and then attempts to take the address of the payload integer and cast it to a character pointer:
void sendTouchStateToServer()
{
    Serial.println("sending state to server");

    uint32_t payload = touchControllerMessageType << 12;
    Serial.println(payload);
    payload |= currentTouchState;

    Serial.print("Payload contents: ");
    Serial.println(payload);
    Serial.print("Payload contents cast as character pointer: ");
    Serial.println((char *)&payload);
    Serial.print("Payload size: ");
    Serial.println(sizeof(payload));

    client.sendBinary((char *)&payload, sizeof(payload));
}

The issue is that while the integer version of the payload looks fine, when I try to cast it into a character pointer the contents is wrong.

I've also tried creating a payloadPointer and directly set the address of the integer as the pointer address, but this also fails.

(I should take this moment to say I'm still pretty green to arduino cpp concepts like this).
What's the right way of doing this? I'm reading up on pointers and trying to understand how to properly do it, but I can't quite figure it out. Could someone explain the correct way of doing it and why? I want this to work, but more than that I want to understand the "why and how" of the proper way.
Thanks! :bows:

Your code with sendBinary is probably fine, as long as on the other side you also use a function that expects to receive exactly 32 bits of binary data (in little-endian format).
Trying to print (char*)&some_32bit_int on the other hand will not do anything useful.
The short version is this:

if you want to send (or receive) binary data, use functions made for binary data - they will usually take a pointer to char (or uint8_t or something like that) and a length.
if you want to send (or receive) strings, use functions meant for strings. They'll sometimes take String, or std::string or, unfortunately perhaps, char * for C strings.

Never mix both.
Functions that expect a (C) string expect it to actually be a C string, i.e. a sequence of chars ending with a null byte (0x00). The chars are expected to be mostly ASCII printable characters. If you give them just plain raw data like the memory address of an int, you won't get what you want.
Trying to print raw data using a function that expects a C string will result in garbage (or nothing at all, or a lot more garbage than you expected!). (Details in the second part.)
If you want to format your data into a string for sending (using a string/text protocol), then use functions like sprintf to do the conversion. (Or use a library that does JSON if your receiver is a web thing - that's pretty handy.)
e.g.
char buffer[32];
sprintf(buffer, "{data:%d}", payload);

Then send buffer via a function that expects a C string.

Consider this:
uint32_t payload = 0x00323130;

The first line initializes a 32 bit int to a specific value, 0x00323130 in hex. Now let's assume that payload was stored in memory at address 0x0100. The memory after that assignment would look like this:
Addr.  Val
0x0100 0x30  // our same number 0x00323130 stored in little-endian format
0x0101 0x31
0x0102 0x32
0x0103 0x00

When you do:
client.sendBinary(&payload, 4);

Those four bytes get send over the wire (or the air) exactly as they are. Nothing more, nothing less. If that's what the receiver expects you're golden.
Now if you do:
Serial.println((char *) &payload);

Serial.println is an overloaded function. When you give it a char *, it expects a C-string, which is a series of characters terminated by a "null byte", i.e. a byte value of zero. Serial.println will then look at the first byte pointed to by the argument. If it's zero, it stops. Otherwise it outputs that char to the serial line, and moves on to the next character. Repeat until a zero byte is found.
In the specially crafted case here with that specific value of payload, Serial.println would receive address 0x0100 and:

Look at the value at 0x0100, get 0x30, check that it's not zero, and pass it on to the serial line. Serial monitor would receive 0x30 and display that. By lucky coincidence this is the ASCII character code for the digit "0".
Look at the value at 0x0101, get 0x31, check that it's not zero, and pass it on to the serial line. Serial monitor would receive 0x31 and display that. By lucky coincidence this is the ASCII character code for the digit "1".
Look at the value at 0x0102, get 0x32, ... serial monitor displays "2".
Loot at the value at 0x0103, get 0x00. That is a null byte, so it stops there, and sends a newline sequence to the serial.

So in this fabricated scenario the output on the serial monitor would be "123".
Try it with payload = 0x00616263; - serial monitor will display "cba".
In short, Serial.println will output exactly the bytes it finds in memory to the serial, until it encounters a zero byte. The serial monitor will try to display those bytes. But, unless you've crafted those values very carefully, all you'll get out of it is garbage - relatively few 8bit values map to printable characters, and even when they do they won't "look" anything like the raw data you had.
If your number happens to start with a zero byte in its binary little-endian representation, Serial.println won't print anything - like if you had given it an empty string.
If your number doesn't contain a zero byte, it will keep on reading memory past the storage allocated for payload until it finds one - possibly outputing much more "junk" than a 32bit variable could ever contain.


Yún vs Uno with Yún Shield What are the differences between an Arduino Yún and a Arduino Uno with an added Yún Shield? And is there a way to expand the storage of the Yún / Yún Shield?

As Majenko wrote: the Arduino Yún = Leonardo + Yún shield. You get into a lot of trouble with the Arduino Uno, and the Yún shield has already enough troubles on its own.

Maybe the Arduino Mega 2560 can be used when both the hardware and software is changed to use another hardware serial port for the Yún shield. If you start with the Yún shield, then use the Leonardo. Don't even try the Arduino Uno.

It is possible to upload a sketch via Ethernet or WiFi, but that often fails. Therefor you need the usb-serial connection to the computer to upload a sketch.

Even when you use a Arduino Leonardo, the communication between the Yún shield and the Arduino board (the 'Bridge') can cause troubles. In OpenWRT a Python script is used to read the serial data from the 'Bridge', which causes a lot of CPU usage.

The Yún shield is not fully compatible with the Arduino Yún. I think a few GPIO pins are different and maybe some other things. That means you are stuck to the firmware of the Yún shield, which can have issues and is not fully compatible with the Arduino Yún firmware.

When installing software in OpenWRT, the rootfs is filled quickly. You can type df or df -h to see the disk usage. I have read about ways to add a SD memory card or a USB flash drive to the rootfs. I have not tried that because I want OpenWRT to run even without a SD memory or USB drive.

An SD memory or USB drive can be used to store a website on it, or scripts, or music files, and so on.

When you need more memory, you might want to try the Raspberry Pi. The Raspberry Pi Zero W is very cheap and has WiFi.


Unable to add multiple potentiometer in Midi controller I am building a simple arduino based midi controller to send cc midi messages. However I am able to send messages only through A0 (analog input).. Any help on this will be appreciated,..

    #include <MIDI.h>
int pot[] = {A0,A1,A2};
int AnaPinsNum = 3;
int potIn[] = {0,0,0};
int analogValue = 0;

int lastAnalogValue[] = {0,0,0};

 void setup()
 {
  MIDI.begin(4);
  // 115200 hairless MIDI
  Serial.begin(115200);
  int i;
  for (i = 0; i < 3; i++);
 }
 void loop() {

  int i;
  for (i = 0; i < AnaPinsNum; i++)

  potIn[i] = analogRead(pot[i])/8;

  // potentiometer could be too sensitive and
  // give different (+-1) values.
  // send CC only when the difference between last value
  // is more than 1
  if ((potIn[i]-lastAnalogValue[i]) > 1 || (potIn[i]-lastAnalogValue[i]) < -1) {
    // value changed?
    if (potIn[i] != lastAnalogValue[i]) {
      // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      MIDI.sendControlChange(1, potIn[i], 1);
      lastAnalogValue[i] = potIn[i];
    }
  }

}

Your logic is flawed here:

  int i;
  for (i = 0; i < AnaPinsNum; i++)
    potIn[i] = analogRead(pot[i]) / 8;

  // potentiometer could be too sensitive and
  // give different (+-1) values.
  // send CC only when the difference between last value
  // is more than 1
  if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1) {
    // value changed?
    if (potIn[i] != lastAnalogValue[i]) {
      // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
      // more info: http://arduinomidilib.sourceforge.net/a00001.html
      MIDI.sendControlChange(1, potIn[i], 1);
      lastAnalogValue[i] = potIn[i];
      }
    }

The first three lines read all three analog pins:

  int i;
  for (i = 0; i < AnaPinsNum; i++)

    potIn[i] = analogRead(pot[i]) / 8;

However then, outside the loop, you are using the value of i which will now be 4, and outside the array bounds. You need to bracket the whole lot, eg.

  int i;
  for (i = 0; i < AnaPinsNum; i++)
    {   // <------------------------------- add this
    potIn[i] = analogRead(pot[i]) / 8;

    // potentiometer could be too sensitive and
    // give different (+-1) values.
    // send CC only when the difference between last value
    // is more than 1
    if ((potIn[i] - lastAnalogValue[i]) > 1 || (potIn[i] - lastAnalogValue[i]) < -1)
      {
      // value changed?
      if (potIn[i] != lastAnalogValue[i])
        {
        // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1)
        // more info: http://arduinomidilib.sourceforge.net/a00001.html
        MIDI.sendControlChange(1, potIn[i], 1);
        lastAnalogValue[i] = potIn[i];
        }  // end of not same as before
      }   // end of value changed
    }   // <----------------- add this

  If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2.

If I understand your question correctly:

Change:

MIDI.sendControlChange(1, potIn[i], 1);

to:

MIDI.sendControlChange(i, potIn[i], i);


Slow speed with stepping motor I am currently working on a project where I need a stepping motor and a servo running at the same time, the servo turns fine and the speed is ok, but the stepping motors speed is very slow and as a result it is loud. I tried the code for the stepping motor on its own and it runs faster, but when it is ran with the servo it is slow. I have follwed a few tutorials to get this to the stage it is at currently, I have removed any delays that i could find which did help a little, but it is still not enough.

The servo is powered from the arduino and the stepping motor is powered by a 12v plug. I am just not sure if there is something within this code that is causing it to slow down? Thank you for you time! The code that it is running slow from is here:

#include <Servo.h>

Servo myservo;

// Configurable Variables
int MaxServoTurn = 20;

// Spooky Variables
int pos = 0;
int customDelay;
int customDelayMapped;
const int pin_LED = 10;
const int pin_switch = 8;
const int stepPin = 3;
const int dirPin = 4;
boolean oldSwitchState = LOW;
boolean newSwitchState1 = LOW;
boolean newSwitchState2 = LOW;
boolean newSwitchState3 = LOW;
unsigned long timeNow = 0;
unsigned long timePrev = 0;
unsigned int timeWait = 100;
boolean flashingLEDisON = false;
boolean LEDstatus = LOW;
boolean keyPressed = false;
boolean buttonToggle = false;

// Setup only, call functions in here
void setup() {
  myservo.attach(9);
  //Sets the two pins as Outputs
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
  //Enables the motor to move in a particular direction
  digitalWrite(dirPin, HIGH);
  pinMode(pin_LED, OUTPUT);
  digitalWrite(pin_LED, LOW);
  pinMode(pin_switch, INPUT);
}

// This is the main controller for the application
void loop() {
  for (pos = 0; pos <= MaxServoTurn; pos += 1) {
    buttonLoop();
    if (buttonToggle == true) {
      myservo.write(pos);
      setupPotentiometer();
    }
  }
  for (pos = MaxServoTurn; pos >= 0; pos -= 1) {
    buttonLoop();
    if (buttonToggle == true) {
      myservo.write(pos);
      setupPotentiometer();
    }
  }
}

void buttonLoop() {
  newSwitchState1 = digitalRead(pin_switch);
  newSwitchState2 = digitalRead(pin_switch);

  newSwitchState3 = digitalRead(pin_switch);

  if (  (newSwitchState1 == newSwitchState2) && (newSwitchState1 == newSwitchState3) )
  {
    if ( newSwitchState1 != oldSwitchState )
    {
      if ( newSwitchState1 == HIGH ) {
        keyPressed = true;
        buttonToggle = true;
      } else {
        keyPressed =  false;
        buttonToggle = false;
      }
      oldSwitchState = newSwitchState1;
    }
  }

  if ( keyPressed )
  {
    // turn on or turn off the blinking LED
    if ( flashingLEDisON == false)
    {
      flashingLEDisON = true;
    }
    else
    {
      flashingLEDisON = false;
      // the LED may be on so to be safe we turn it off. If you wished you could check LEDstatus
      LEDstatus = LOW;  digitalWrite(pin_LED, LEDstatus);
    }
    keyPressed = false;
  }

  // if the blinking LED is on. See if it is time to blink it
  if ( flashingLEDisON == true )
  {
    timeNow = millis();
    if (timeNow - timePrev >= timeWait )
    {
      timePrev = timeNow;
      if (LEDstatus == LOW) {
        LEDstatus = HIGH;
      } else {
        LEDstatus = LOW;
      }
      digitalWrite(pin_LED, LEDstatus);
    }
  }
}

void setupPotentiometer() {
  customDelayMapped = speedUp(); // Gets custom delay values from the custom speedUp function
  // Makes pules with custom delay, depending on the Potentiometer, from which the speed of the motor depends
  digitalWrite(stepPin, HIGH);
  delayMicroseconds(customDelayMapped);
  digitalWrite(stepPin, LOW);
  delayMicroseconds(customDelayMapped);
}

// Function for reading the Potentiometer
int speedUp() {
  int customDelay = analogRead(A0); // Reads the potentiometer
  int newCustom = map(customDelay, 0, 1023, 300, 4000); // Convrests the read values of the potentiometer from 0 to 1023 into desireded delay values (300 to 4000)
  return newCustom;
}

I had a project where I needed to run two steppers at the same time as they were moving a heavy load and were moving the same piece.

While a servo is going to move the desired spot, a stepper will not.

In the process of setting up the stepper you designated steps per rev and amount of steps to take at a time.

The stepper is only going to move the "amount of steps" at a time for each run of the code. I ran into a similar  problem and I had to put in a 2ms delay after the servo run command to make the motors run smoother and faster, other wise it sounded like a bunch of gears gnashing and skipping.  These steppers were facing each other that is why they move opposite directions.

if (down==true){
  TLstep.step(-step1);
  TRstep.step(step1);
  delay(2);
}

I know it been a year since this was looked at. Hope you got your issue figured out.


How to stop Arduino from drawing power through USB I'm working on an embedded project, where I use arduinos as a "sensor shield" for RaspberryPi (I have model B).

The problem is, that the RaspberryPi's USB port is not powerfull enough to drive WiFi adapter and arduino with sensors. The solution is easy, I will power the sensors externally, not through the RPi.

But I was wondering, is it possible to power whole Arduino externally (through Vin) and use the USB only for serial communication.

To clarify, I know how to solve my problem - use some other mean of communication, than USB - GPIO serial, I2C, wireless, etc... I'm just interested if the whole thing will work, with USB cable which has 5V lead cut, for example.

The main issue I can see with this is, that the USB<->Serial chip is powered through USB only, then it will now work.

If you provide power to the Arduino through Vin this will disconnect USB power through the MOSFET switch.


Simple Arduino Code Not Working When I upload this code LED at pin 13 goes HIGH and that's it. My goal is to make it blink in the order specified in the array. What am I doing wrong?

int Array[] = {1,1,1,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0};
int Data = 13;
int i = 0;

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

void loop() {
    int x = Array[i];
    delay(200);
    digitalWrite(Data, x);
    i = i+1;
    if (i==23) {
        i=0;
    }
}

What you're doing wrong is living your life at a normal speed.

The LED will be blinking, but so fast you can't see it change.

Without adding some delays in there you will just see the LED light up.


Best way to implement score board logic using Arduino and Shift Registers? I am from a mobile development background and very new to Arduino. I am trying to make an electronic cricket score board. The logic is simple.

Score - 888 (3 Digits) - I have implemented this logic using shift registers.  Three pin used from Arduino Uno and this is working fine.

Overs - 88 (2 Digits) - Need to find a best way to implement it

Wickets - 8 (1 Digit) - Need to find a best way to implement it

Now I need to add Wickets and Overs to the logic. I think there are two ways to do it.

One is passing data from Score shift registers. I think this way is a bit complicated in logic level. But if this is a good way, then great.
The other is, connect to Arduino Uno pins directly rather than getting information from score shift registers.  There are only few pins.

Please Note: I need to print this design in PCB

This might be a basic question. But I would like to the know which way is efficient, and its advantages. If both are not, I would like to the know the best one.

There isn't really a best way (and such questions are usually discouraged as they can easily descend into argument).

Personally I would go for chaining all of the '595s together so you only ever use the 3 pins; it gives you the opportunity to use a smaller MCU like the ATtiny when you put it all on a board later which makes it (slightly) cheaper and (potentially) smaller.

From a software point of view, it doesn't make a huge amount of difference - doing it the way I have suggested means you send the 3 values out in the correct order every time one of them updates. Separating the 3 scores with their own dedicated pins means juggling which one needs to be updated each time. Neither option is particularly complicated and with this sort of application efficiency of code is mostly redundant because the entire MCU is dedicated to the (simple) task.


Why is timer0 the fastest timer in the arduino? In the documentation, it shows that the higher  frequency that can be reached with an Arduino UNO for and 8bits PWM is using timer0  with the pre-scaler  set at 1. That  gives a Fs of 62500 Hz, but why is that so?

I understand the Prescaler is dividing the frequency, but why it does start at 62500 Hz and  timer1 and timer2 have as maximum 31372 Hz.

Timers 1 and 2 are configured by the Arduino core library to run the so
called “phase correct PWM” mode. In this mode, the timers count
forward from 0 to 255, and then they count backwards to zero. Timer 0 is
configured by the same library in “fast PWM” mode, where it counts
from 0 to 255 and then overflows back to zero in a single timer cycle.

You can, if you want, configure timers 1 and 2 in fast PWM mode. For
doing this, you will have to access their I/O registers directly. C.f.
the datasheet of the relevant microcontroller for details.

A couple of links:

the datasheet of the
ATmega328P
microcontroller describes all the possible configurations of the
timers (sections 15, 16 and 18 for timer 0, 1 and 2, respectively)
the source code of the Arduino init()
function
to see how Arduino core configures them.


Serial loop stopped after a while, I don't know why I am very new to Arduino. I wrote a program in order to read some registers in a I2C device. I receive HEX datas.

So the Arduino LEONARDO is connected to the external board using the 2-wires-bus.
Then informations are sent to my computer by using Serial.println.

My problem is my Arduino stops working after a while, maybe 25 or 30 loops. Sometimes I loose communication and I have to reboot the Arduino.

I guess it's an overflow issue or I'm loosing connection randomly :

int dt = 500;
int dt2 = 1000; // used for delay duration
#include "Wire.h"
#include <Process.h>
#define pot_address 0x25 // each I2C object has a unique bus address, the MCP40

void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial.begin(9600);

}

void loop() {
  // put your main code here, to run repeatedly:

  Wire.beginTransmission(pot_address);
  Wire.write(0); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
  byte b = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(1); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte c = Wire.read();

   Wire.beginTransmission(pot_address);
  Wire.write(2); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte d = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(3); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte e = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(4); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte f = Wire.read();

  Serial.print("b");
  Serial.println(b, HEX);
  Serial.println("-");
  Serial.print("c");
  Serial.println(c, HEX);
  Serial.println("-");
  Serial.print("d");
  Serial.println(d, HEX);
  Serial.println("-");
  Serial.print("e");
  Serial.println(e, HEX);
  Serial.println("-");
  Serial.print("f");
  Serial.println(f, HEX);
  Serial.println("-");

 delay(dt2);

}

Add:

while(!Serial) ;

I'll make sure the Leonardo is in sync with the Serial communication.

It is the case because the Leonardo is USB native thus the Serial communication works differently.