text:
Change UART pin
I am developing GPRS HTTP send request code using a GSM/GPRS module. I found the following code via google:

/*************************************************************************
* SIM800 GPRS/HTTP Library
* Distributed under GPL v2.0
* Written by Stanley Huang <stanleyhuangyc@gmail.com>
* For more information, please visit http://arduinodev.com
*************************************************************************/

#include <Arduino.h>

// change this to the pin connect with SIM800 reset pin
#define SIM800_RESET_PIN 7

// change this to the serial UART which SIM800 is attached to
#define SIM_SERIAL Serial

// define DEBUG to one serial UART to enable debug information output
//#define DEBUG Serial

typedef enum {
    HTTP_DISABLED = 0,
    HTTP_READY,
    HTTP_CONNECTING,
    HTTP_READING,
    HTTP_ERROR,
} HTTP_STATES;

typedef struct {
  float lat;
  float lon;
  uint8_t year; /* year past 2000, e.g. 15 for 2015 */
  uint8_t month;
  uint8_t day;
  uint8_t hour;
  uint8_t minute;
  uint8_t second;
} GSM_LOCATION;

class CGPRS_SIM800 {
public:
    CGPRS_SIM800():httpState(HTTP_DISABLED) {}
    // initialize the module
    bool init();
    // setup network
    byte setup(const char* apn);
    // get network operator name
    bool getOperatorName();
    // check for incoming SMS
    bool checkSMS();
    // get signal quality level (in dB)
    int getSignalQuality();
    // get GSM location and network time
    bool getLocation(GSM_LOCATION* loc);
    // initialize HTTP connection
    bool httpInit();
    // terminate HTTP connection
    void httpUninit();
    // connect to HTTP server
    bool httpConnect(const char* url, const char* args = 0);
    // check if HTTP connection is established
    // return 0 for in progress, 1 for success, 2 for error
    byte httpIsConnected();
    // read data from HTTP connection
    void httpRead();
    // check if HTTP connection is established
    // return 0 for in progress, -1 for error, bytes of http payload on success
    int httpIsRead();
    // send AT command and check for expected response
    byte sendCommand(const char* cmd, unsigned int timeout = 2000, const char* expected = 0);
    // send AT command and check for two possible responses
    byte sendCommand(const char* cmd, const char* expected1, const char* expected2, unsigned int timeout = 2000);
    // toggle low-power mode
    bool sleep(bool enabled)
    {
      return sendCommand(enabled ? "AT+CFUN=0" : "AT+CFUN=1");
    }
    // check if there is available serial data
    bool available()
    {
      return SIM_SERIAL.available();
    }
    char buffer[256];
    byte httpState;
private:
    byte checkbuffer(const char* expected1, const char* expected2 = 0, unsigned int timeout = 2000);
    void purgeSerial();
    byte m_bytesRecv;
    uint32_t m_checkTimer;
};

The problem is I have no idea how to change or define Rx and Tx Pin. If I define SIM_SERIAL serial1 it's showing me error. I want to change it to pins 10 and 11.
Here is other code whenever I try to compile it shows me error on "serial1" online. above code is sim800.h file
here is program code of send data through http
"SIM800.h"

#define APN "connect"
#define con Serial
static const char* url = "http://arduinodev.com/datetime.php";

CGPRS_SIM800 gprs;
uint32_t count = 0;
uint32_t errors = 0;

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

  con.println("SIM800 TEST");

  for (;;) {
    con.print("Resetting...");
    while (!gprs.init()) {
      con.write('.');
    }
    con.println("OK");

    con.print("Setting up network...");
    byte ret = gprs.setup(APN);
    if (ret == 0)
      break;
    con.print("Error code:");
    con.println(ret);
    con.println(gprs.buffer);
  }
  con.println("OK");
  delay(3000);

  if (gprs.getOperatorName()) {
    con.print("Operator:");
    con.println(gprs.buffer);
  }
  int ret = gprs.getSignalQuality();
  if (ret) {
     con.print("Signal:");
     con.print(ret);
     con.println("dB");
  }
  for (;;) {
    if (gprs.httpInit()) break;
    con.println(gprs.buffer);
    gprs.httpUninit();
    delay(1000);
  }
  delay(3000);
}

void loop()
{

  char mydata[16];
  sprintf(mydata, "t=%lu", millis());
  con.print("Requesting ");
  con.print(url);
  con.print('?');
  con.println(mydata);
  gprs.httpConnect(url, mydata);
  count++;
  while (gprs.httpIsConnected() == 0) {
    // can do something here while waiting
    con.write('.');
    for (byte n = 0; n < 25 && !gprs.available(); n++) {
      delay(10);
    }
  }
  if (gprs.httpState == HTTP_ERROR) {
    con.println("Connect error");
    errors++;
    delay(3000);
    return;
  }
  con.println();
  gprs.httpRead();
  int ret;
  while ((ret = gprs.httpIsRead()) == 0) {
    // can do something here while waiting
  }
  if (gprs.httpState == HTTP_ERROR) {
    con.println("Read error");
    errors++;
    delay(3000);
    return;
  }

  // now we have received payload
  con.print("[Payload]");
  con.println(gprs.buffer);

  // show position
  GSM_LOCATION loc;
  if (gprs.getLocation(&loc)) {
    con.print("LAT:");
    con.print(loc.lat, 6);
    con.print(" LON:");
    con.print(loc.lon, 6);
    con.print(" TIME:");
    con.print(loc.hour);
    con.print(':');
    con.print(loc.minute);
    con.print(':');
    con.println(loc.second);
  }

  // show stats
  con.print("Total Requests:");
  con.print(count);
  if (errors) {
    con.print(" Errors:");
    con.print(errors);
  }
  con.println();
}

i already know how to send data through http using AT command and software serial library here is  my code
#include <SoftwareSerial.h>

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

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

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.write("AT\n");
  delay(1000);
  mySerial.write("AT+CSQ\n");
  delay(1000);
  mySerial.write("AT+SAPBR=3,1,\"APN\",\"internet\"\n");
  delay(2000);
  mySerial.write("\nAT+SAPBR=1,1\n");
  delay(1000);
  mySerial.write("AT+HTTPINIT\n");
  delay(1000);

}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
    delay(1000)
    serial.print(enter key)
  }
  if (Serial.available()) {
    delay(2000);
     mySerial.write("AT+HTTPPARA=\"URL\",\"http://www.mydomain.in/index.php?dt=testdata\"\n");
     delay(2000);
     mySerial.write("AT+HTTPACTION=0\n");
      delay(2000);
      mySerial.write("\n");
    mySerial.write(Serial.read());
  }

In this code I define Rx Tx (UART)pin. Can you please suggest me any idea how can i define RX Tx pin in sim800.h file. because serial1 give me error on compiling time

That doesn't look like your code.

yes i said i found code on google

How would you possibly expect us to be able to tell you what to change it to without seeing any of your code?

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

Well there you are.
#define SIM_SERIAL mySerial

thank you. should i add SoftwareSerial mySerial(10, 11); // RX, TX code in sim800.h file  above #define SIM_SERIAL

I think Serial1 has to do with the Hardware serial Port(tx1,rx1) on Arduino mega . But since you are not using Serial.print i suggest you try "Serial/Serial0" if you are using UNO.
If you want (10,11) like you said then i think you should use Softwareserial
 #include SoftwareSerial.h //check spelling online not sure
SoftwareSerial allex(10,11);
 #define SIM_SERIAL  allex
 try it and see if it works.

should i change #define con Serial also..

i set default serial port using only serial declaration but default RX and TX pin not working

I change sim800.h code "#define SIM_SERIAL mySerial" to "#define SIM_SERIAL Serial'


text:
Problem regarding Arduino & GSM module kit
I am using the following program to receive messages from a GSM module.
As we start our kit, we received two messages "main door is open" and "store room is open". (Depending upon sensor position)
This program is run properly, but the problem is that it repeats the message after some time. It does not depend on time.
Suppose our store room is closed. I receive this message on my given mobile number, but after some time two "the store room is open" messages are received and after this message immediately the message "received store room is closed". (means it sets sensor to its initial mode i.e. closed) Same problem is happening with this main door.
My kit contains an Arduino UNO board, GSM module SIM800 and two limit switches (one for the main door and second is for the store room)
I keep my both sensor and Arduino board distance over 17 meters by using CAT5e cable.
My code:
const int Main = 7;  // pin define for main door sensor
const int Store = 8; // pin define for store room sensor
const int Main_led =  13;  // indication for main door sensor
const int Store_led =  14;  // indication for store room sensor

void setup() {
  Serial.begin(9600);
  pinMode(Main_led, OUTPUT);
  pinMode(Store_led, OUTPUT);
  pinMode(Main, INPUT);
  pinMode(Store, INPUT);
}

void sendMessage(char *text) {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"+91-------------");
    Serial.print("\"\r\n");
    delay(5000);
    Serial.print(text);
    Serial.write(0x1A);
    delay(5000);
}

void loop() {
  static int oldState1 = -1;
  static int oldState2 = -1;

  int buttonState1 = digitalRead(Main);
  if (buttonState1 != oldState1) {
    digitalWrite(Main_led, buttonState1);
    if (buttonState1 == HIGH)
      sendMessage("Main Door is closed");
    else
      sendMessage("Main Door is open");
    oldState1 = buttonState1;
  }

  int buttonState2 = digitalRead(Store);
  if (buttonState2 != oldState2) {
    digitalWrite(Store_led, buttonState2 );
    if (buttonState2 == HIGH)
      sendMessage("Store room is closed");
    else
      sendMessage("Store room is open");
    oldState2 = buttonState2;
  }
}

Do the LEDs reflect the messages when you get these odd messages?  It sounds like there is a "glitch" in the sensor data, the equivalent of a switch bouncing, if so add some de-bouncing code.  When a sensor reports a change in state, wait one second (ish) before reporting the change in state.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Why are there two sets of tools and bootloaders in the Arduino IDE?
After digging around on a separate problem, I found that avrdude, avr-gcc and some more tools can be found in two different locations:
(1): C:\Program Files\Arduino\hardware

(2): C:\Users\<user>\AppData\Local\Arduino15\packages\arduino

These two folders also both contain similar copies of the hardware directory where all the bootloader hex-files and source code is stored:
(3): C:\Program Files\Arduino\hardware\arduino\avr

(4): C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.17

I say similar because the bootloaders\caterina folder in (4) contains quite a few hex-files that are missing in (3).
When burning a bootloader, looking at verbose output from the Arduino IDE reveals that hex-file and executable of avrdude from (2) are used, not (1).
What is the reason for this? My guess would be that location (1) is deprecated, but why choose to put stuff like this into Appdata in the first place?

My guess if that 1) if from a previous version. Did you ever update Arduino?

@Gerben I just checked by uninstalling Arduino completely and then reinstalling it. The files in (1) are still there.

Arduino IDE comes with a "platform" (the arduino AVR) in the Arduino\hardware folder.
Then you can add/upgrade platforms with the boards manager.
These will be installed in C:\Users\\AppData\Local\Arduino15\packages.
The reason for this is that Arduino IDE wants to be able to "work out of the box".
If they did not deliver the platform inside the installation/zip a "installation finishing" job needs to run after opening the Arduino IDE.

If that was the case, that would mean that location (4) only contained files of additional board packages. But that's not the case. I just reinstalled and it seems like all arduino files are already in (4) as they were before. The additional boards I had installed are missing now.

Removing the Arduino IDE does not remove the content of C:\Users\AppData\Local\Arduino15\packages.
When you upgrade the avr board they will be in C:\Users\AppData\Local\Arduino15\packages. and those will be used (arduino IDE only supports 1 version of each platform)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
How to empty the buffer for Serial port?

I have a Yun that accepts commands via the bridge (note the below code is part of a very simple virtual keyboard that accepts commands then runs Keyboard.println on them:
#include <stdlib.h>
#include <string.h>
HardwareSerial *port;

void setup() {
  port = &Serial1;
  port->begin(9600);
}

void loop() {
  if (port->available()) {
    String cmd = port->readString();

    if(cmd.length() > 1){
      String instruction = cmd;
      int arg_comma_index = 0;
      arg_comma_index = instruction.indexOf(",");
      String func = instruction.substring(0, arg_comma_index);
      String args = instruction.substring(arg_comma_index + 1, instruction.length() + 1 );

      Keyboard.begin();
      Keyboard.println(args);
      Keyboard.end();
    }
    port->read(); // Try to throw away whatever's left to prevent looping (which is still happening).
  }
}

If I send it a short string:

The first time, immediately after starting the sketch, it works.
The second time, it works but loops anywhere from 1-5 times.
The third time, it loops more times still.
If I leave the device running (even if not operating it), the number of times it loops goes up when I finally do send it an instruction. I'm seeing 20-75 loops after less than 15 minutes of uptime.

Clearly the loops where no instruction is being received are still building up something here. I've tried:

Restarting the port each void loop().
Flushing the port at the top and/or bottom of each void loop().
Setting cmd = "" at the end of each void loop().
Checking peek(), available(), and readString() - after I send it one instruction, they return the same values every single time they loop.

It's quite simple to empty the serial buffer - you just read all the data that is in the buffer and throw it away:
while (port->available()) {
    port->read();
}

Thank you! Unfortunately, this isn't fixing my looping problem. I put port->read(); at the end of my loop but it is still running a variable number of times.

Maybe if you posted your real code instead of some mashup of c and basic we might be able to help you better.

I've posted the code.

That is quite some code. I can't fathom quite what you're attempting to do there.  I think your main problem is that you are using readString() which doesn't do what you think it does.  I think you want readString('\n') to read up to a newline (or whatever terminator you choose) character. Also, what is all the rest meant to be doing? Whatever it is you seem to have made it overly complex and bizarre.  Please expand your question with what you intend it to do.

The code I posted above is a much-shortened snippet of the original code, but it displays the same issue (I shortened it for easier reading and debugging). The device is a simple virtual keyboard, accepting some commands over the bridge and outputting them with Keyboard.println.

To your point about readString(), I do want to read the entire buffer into cmd. I assume using readString('\n') instead would have the same effect if \n were at the end of the line?

readString() will read until it fails to read for 1 second. readString('\n') will read until it fails to read for 1 second or receives a newline. Oh and do yourself a favour and lose the crutch of the String class.

I wouldn't be using readString myself. In fact I wouldn't be using the String class at all. readString keeps reading until it times out (by default after one second), so it may read more - or less even - than you want. It will also introduce a one-second delay while it sits around waiting for that second to elapse.
You are much better off doing a non-blocking loop, and then processing data when you get a known delimiter, like a newline or comma, or whatever you designate as "ending the stream". Example code that uses a newline delimiter:
// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void setup ()
  {
  Serial.begin (115200);
  } // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data)
  {
  // for now just display it
  // (but you could compare it to some value, convert to an integer, etc.)
  Serial.println (data);
  }  // end of process_data

void processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
    {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

    }  // end of switch

  } // end of processIncomingByte

void loop()
  {
  // if serial data available, process it
  while (Serial.available () > 0)
    processIncomingByte (Serial.read ());

  // do other stuff here like testing digital input (button presses) ...

  }  // end of loop

In my example code you would do whatever-it-is you want in process_data which is called once an entire line arrives. Then you don't need to discard incoming data (empty the serial buffer), which seems to me to be a bad idea anyway.

How do you send your commands, char by char or one shot ?
If there is nothing to read, port->available() may return -1 error code after 1 sec, but you already checked, isn't it ? Anyway, you should check if it returns something > 0 instead of something != 0.
Note that readString() doesn't take any parameter (https://www.arduino.cc/en/Reference/StreamReadString). I suspect this function not acting as read() to decrease the number returned by available();
If you want to catch \n, use readStringUntil('\n') instead (https://www.arduino.cc/en/Serial/ReadStringUntil).
Try to put the full code (with the loop) given by Majenko at the end of your loop() function.
#include <stdlib.h>
#include <string.h>
HardwareSerial *port;

void setup() {
  port = &Serial1;
  port->begin(9600);
}

void loop() {
  if (port->available() > 0) {
    String cmd = port->readString();

    if (cmd.length() > 1) { // Why not 0 ?
      String instruction = cmd;
      int arg_comma_index = 0;
      arg_comma_index = instruction.indexOf(",");
      String func = instruction.substring(0, arg_comma_index);
      String args = instruction.substring(arg_comma_index + 1, instruction.length() + 1 );

      Keyboard.begin();
      Keyboard.println(args);
      Keyboard.end();
    }
    while (port->available() > 0) {
        port->read();
    }
  }
}

I suspect this function not acting as read() to decrease the number returned by available(); - readString will indeed read (and decrease the number in the buffer) however it just reads until it times out, so it could read more, or less even, than is required.


text:
Convert a Serial string to a sketch command on Yun?
How can I convert a string like the following:
"pinMode(2, INPUT_PULLUP)"

or

'Keyboard.print("Hello world")'

into actual code that the Arduino can act on?

You can't - not directly.
There are two things you can do:

Build your "command" into a sketch and compile it, then upload it in to the Yun's AVR chip.  The compiling will have to be done on your PC, and the HEX file uploaded to the AVR (you can do it directly through the Yun's web interface).
Don't send sketch code, but send pre-defined instructions like "Turn on pin 3" which your sketch then interprets.  That could be as simple as two bytes "P3" for instance.  It's entirely up to you how you craft that.

Firmata might help with option 2 if uploading a new sketch every time isn't what you want to do.

There is a third option: install an interpreter on the Arduino, then
just send it the program you want it to run. There are a few such
interpreters available. A quick search showed:

Bitlash, a C-like language
iArduino, another
C-like language
FlashForth, a
Forth
implementation
FINF Is Not Forth, a Forth-like
language

There are probably many others.
The difference between this option and Majenko's option 2 is that this
would allow you to send a complete program, with functions,
conditionals, loops, etc., whereas with a Firmata or similar approach
you would keep the program logic (functions, loops, conditionals) on the
host computer, and only send simple commands to the Arduino.

You might also try the Firmata library, too.
It provides similar functionality, and there are some libs for the computer side of it, if you are so inclined.


text:
Simultaneous output from sonar array
I am working on a project that records the elevation changes of a 1 foot wide section using sonar distance measurement. I have 10 HC-SR04 sensors arranged in a straight line over this 1 foot section.
The issue I am having is that when I send an output from my sonar sensor, I must wait until the return signal is recorded before I can trigger the next sonar sensor to take a measurement. This is rather slow and decreases the sampling frequency significantly. I need each sonar sensor to take 1000 measurements per second for my project.
Is there a way to have the HC-SR04 sensors simultaneously output and listen for the return signal? I would want all 10 sensors to send a 40 kHz pulse at the same time, and then when a return signal is recorded, another 40 kHz pulse is sent out.
The average distance to the 1 foot wide section is about 11 inch. If the Arduino is limited and there are other control boards that can accomplish this, it would help a lot if you can point me in the right direction.

1000 measurement for 10 sensors per seconds, it means there are 10000 measurement per sec with 0.1 mS time slot for each measurement.
According to SRF-04 Documentation,
(1)

If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.

So, time slot for each reading is 36 mS ("if" nothing is detected), which means for 10 SRF04 x 1000 reading, it will take 360000 mS = 360 Sec.
(2)

I would want all 10 sensors to send a 40kHz pulse at the same time, and then when a return signal is recorded, another 40kHz pulse is sent out.

Its seems reasonable. But,

According to the timing diagram, 1 cycle minimum period consist of :

100 us Trigger pulse ==> 0.0001 s
8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
100 us Echo pulse ==> 0.0001 s
10 ms delay time ==> 0.01 s

Total for 1 cycle is 0.0104 s, so for 1000 readings x 10 sensors (object to detect is present) will be 104 s.
All sensor burst at the same frequency, great idea. However it's not advised (or rather not possible) because that will disturb each sensor reading unless you successfully change each sensors frequency or doing sound modulation. Even if you success in modulating 10 sensors frequency, the needed time is still not met 1 s interval

100uS for 10 sensors trigger pulse at once ==> 0.0001 s
8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
100 us (minimum) Echo pulse --> 0.0001 s x 10 sensors ==> 0.001 s, because Arduino does not support threading, which mean there is no way you can read all at same time
10 ms delay time ==> 0.01 s

Time for 1 cycle (10 sensors reading): 0.0113, 1000 readings : 11.3 s
(3)
"How about changing the beam pattern?"

Changing beam pattern and beam width
You can't! This is a question which crops up regularly, however there is no easy way to reduce or change the beam width that I'm aware of. The beam pattern of the SRF04 is conical with the width of the beam being a function of the surface area of the transducers and is fixed.

So, rather than trying to modify the ultrasonic, more reasonable solution is changing the way you do elevation measurement.


text:
Analog output doesn't work for just 2 LEDs [Arduino Mega]
I am having a problem with an Arduino Mega 2560.
Everything works fine, the ultrasonic sensors work fine, and the other LEDs work fine. Although there is 2 LEDs who do not work right and when I do analogWrite(), they actually do digitalWrite(). I have tried to attach these two LEDs to a potentiometer (potentiometer works fine, values are tested) but it always does digitalWrite() not analogWrite().
I have tested the LEDs and potentiometer on an Arduino Uno in PWM pins and analog pin and yes it does work very well.
Please mind that these LEDs are attached to analog pins. Why is this? Because I do not have anymore PWM pins available to use and so I have to use analog pins. No way I can rearrange this.
Here is part of the code (only part otherwise it's too long, most of my pins are taken):
//Leds//

int led = A4;
int ledUV = A3;

//Potentiometer//

int potReading;
int potPin = A2;
int lightDim;

void setup(){

    Serial.begin(9600);

    pinMode(led, OUTPUT);
    pinMode(ledUV, OUTPUT);

    pinMode(potPin, INPUT);

}

void loop(){

    potReading = analogRead(potPin);
    lightDim = (255./1023.)*potReading;

    analogWrite(led, lightDim);
//  analogWrite(ledUV, lightDim);
//  Serial.println("pot: ");
//  Serial.println(potReading);
//  Serial.println(" ");
    Serial.println("dim: ");
    Serial.println(lightDim);
//  analogWrite(led, 255);
//  analogWrite(ledUV, 255);

}

< Why is this? "this" being what?

Reference: analogWrite()
The pins 2 - 13 and 44 - 46 are the PWM pins for analogWrite().
That means you have 15 PWM pins. Did you use them all?
You could add a module with more PWM outputs. Search for: Arduino 16 channel PWM
The Arduino Mega does not have analog outputs, only digital PWM outputs.

Thank you so much man it did work! I did not knew about 44-46!

Analog pins an only read analog values, not write them.
analogWrite() is a deceptive name. It should really be PWMWrite() since all it does is PWM. And that, of course, needs PWM pins.

This is a good answer too, but arduino uno analog pins have anolog output, as this procedure and code worked on a uno.

No they don't. There is no analog output on any atmega chips. Whatever you did before it certainly wasn't analog output.

Do you want me to post a video?

I'd love to see that, yes. As well as the code that is doing it.


text:
Why use a motor driver board?
I'm just getting into electronics in general and I'm confused a bit as to why I'd want/need to use a motor driver board instead of just setting up my own transistor/diode/etc when attempting to power and control a DC motor.
Any chance someone could clarify the point to using a motor driver board instead (assuming there is another option as I think there to be)?

It is for simplicity - the board will work without needing to design and build your own circuit. You could design and build your own motor controller, but it would take longer. It is a bit like asking, "why buy a radio when I can make one?" :-)

@Greenonline I actually assumed a single transistor/resister/diode would be sufficient in powering a motor. I wouldn't think to build my own motor driver board knowing now more of what it is/does. That, I believe, was closer to what I should have been asking (what a motor driver board is compared to using a single transistor/diode).

It actually uses 4 transistors, to be able to reverse the motor as well. Some drivers even allow two motors in both directions. One may roll it's own, but a readymade part is usually cheaper than ging through the whole design and test/optimize iterations himself.

A motor driver board is just a convenient way of creating what is known as a "H Bridge". This is an arrangement of 4 (or more, but 4 primary) transistors.
You can make it yourself with discrete transistors, but it is simpler to just use a pre-made chip.

A H Bridge gives you greater control over a motor than a single transistor alone. It allows you to control the direction, which you can't do with a single transistor, and it also gives you access to braking modes where the motor becomes harder to turn thus assisting in slowing down the load.
With a single transistor you can turn the motor on and off (or vary the speed if you use PWM) but that is all.

simulate this circuit – Schematic created using CircuitLab

A couple of extra reasons.  If you have low power controllers (like computers), it keep the low power devices away from higher power motor drivers, electronic noise etc.
If you use AC, it can also keep the issues of driving inductive loads away from your micro-electronics (phase and power factor issues).


text:
Speed up the Arduino
I wrote a code that controls a stepper motor using the AccelStepper library. When it receives a serial signal from Visual Basic that contains a coordinate value, the Arduino will control the stepper motor by this value. The code works very well but it runs 1 second after receiving the value over the serial port. I want the code to run faster. Here is the code:
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper(1, 9, 8);

int pos = 0;

void setup()
{
  Serial.begin(115200);
  stepper.setMaxSpeed(90);
  stepper.setAcceleration(90);
}

void loop()
{
  if (Serial.available()) {
    int steps = Serial.parseInt();
    stepper.moveTo(steps);

    if (stepper.distanceToGo() == 0) {
      stepper.moveTo(stepper.currentPosition());
      stepper.setSpeed(100);
    }
  }
  stepper.run();
}

Do not use parseInt(): it will wait for one second to make sure there are no digits pending.

Or you could try just appending a line terminator when sending the number.

Unrelated, but why include accelstepper 3x?

As others have said, this issue is created because the parseInt function reads in characters until it receives a non numeric character or until it reaches the timeout value, which is set at 1000 ms (1 second). There are a couple of ways to fix this, order most difficult to least:

Instead of just sending a number, send a number and then a letter at the end. So instead of sending "123", you would send "123x".  parseInt() will immediately return when it hits the x.  However, you'll still have the x in the stream so you'll need to manually read it and discard it.
Make the value that is sent a set number of digits - say 4 for example.  Since you know it will be four digits, use a for loop to read in four characters and build it into a number by multiplying.  If you read in digit1, digit2, digit3, digit4 then the number is 1000 * digit1 + 100 * digit2 + 10 * digit3 + digit4.
Make the timeout value for parseInt() smaller.  parseInt() inherits from the Stream class so you would use Serial.setTimeout(50) in the setup function to change it to a 50 ms timeout.

Do not use parseInt(): it will wait for one second to make sure there are no digits pending.
-Edgar Bonet

can you  make line terminator on the code because Iam very new to arduino programing please and what I use if replace the parseInt():

how to terminate the serial


text:
Uploading Error: no programmer has been specified
Whenever I upload a code I get this error:
avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

I am able to upload from other PCs, but ever since I got the newest IDE, it stopped working. I even tried downgrading to 1.6.8, and still i get this error... Any help? Thanks,
Sean

Check what programmer you have selected in the IDE.

This issue occurs when using Arduino IDE 1.6.8 or older with Arduino AVR Boards 1.6.12 or 1.6.14. There are two solutions:

Upgrade your Arduino IDE to 1.6.9 or newer by downloading and
installing the appropriate file from
https://www.arduino.cc/en/Main/Software.
Downgrade your Arduino AVR Boards version to 1.6.11 or older(or 1.6.13) via
Tools > Board > Boards Manager...

I submitted a pull request to fix this backwards compatibility issue and it was merged by the Arduino developers so this issue will no longer occur with Arduino AVR Boards 1.6.15 and up. It explains the cause of the issue:
https://github.com/arduino/Arduino/pull/5427


text:
RFID-RC522 Can't access sector after writing to trailer block
I'm currently using an Arduino Uno R3 and an RFID-RC522 with https://github.com/miguelbalboa/rfid .
I wrote the following bytes to the trailer block in order to experiment with it:
byte writeBlockContent[blockSize] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x7, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA };

I wanted to change the default MFRC522::MIFARE_Key key.keyByte so I can read and write to the card using a custom key and leave everything unchanged but I cannot access the sector anymore.
What do I have to do to be able to access the sector again?
Code:
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
/*
 * Pin connections for UNO:
 * 9  - RST
 * 10 - SDA
 * 11 - MOSI
 * 12 - MISO
 * 13 - SCK
 */
MFRC522 mfrc522(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key; // will hold card info

// Every 4th block is a trailer block that contains access and security info, modulo 4.
const int blockSize = 16;

int writeBlockNumber = 2; // The block we want to write the data.
int readBlockNumber = 2;
byte writeBlockContent[blockSize] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x7, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA }; // 16 character max
byte readBlockContent[18] = { 0 };

// Will write the data to the block.
int writeBlock(int block, byte data[]) {
  int status;

  if ( (block + 1) % 4 == 0) {
    Serial.println("Warning: Writing on a trailer block!");
    return 0;
  }

  int trailerBlock = block + (4 - block % 4) - 1;
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &mfrc522.uid);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  status = mfrc522.MIFARE_Write(block, data, blockSize);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("MIFARE_Write() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }
  return MFRC522::STATUS_OK;
}

// Will try to dump the whole card info.
void dumpCard() {
  for(int i = 0; i < blockSize; ++i) {
      Serial.print("Block ");
      Serial.print(i);
      Serial.print(" ");
      if ( readBlock(i, readBlockContent) == MFRC522::STATUS_OK ) {
        printReadBlock();
      }
  }
  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

// Will read the block.
// These functions must be called if you wish to read a new card.
//    mfrc522.PICC_HaltA();
//    mfrc522.PCD_StopCrypto1();
int readBlock(int block, byte data[]) {
  int status;
  byte readSize = blockSize + 2;

  int trailerBlock = block + (4 - block % 4) - 1;
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &mfrc522.uid);

  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  status = mfrc522.MIFARE_Read(block, data, &readSize);
  if ( status != MFRC522::STATUS_OK ) {
    Serial.print("MIFARE_Read() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return status;
  }

  return MFRC522::STATUS_OK;
}

// Will print the contents of the readBlockContent.
void printReadBlock() {
  for (int i = 0; i < blockSize; ++i) {
    Serial.print(readBlockContent[i], HEX);
    Serial.print(" ");
  }
  Serial.print(" -> ");
  for (int i = 0; i < blockSize; ++i) {
    Serial.write(readBlockContent[i]);
  }

  Serial.println();
}

// Will print the card id that is stored in mfrc522.uid.uidByte
void printCardUid() {
  Serial.print("Card ID: ");
  for (int i = 0; i < mfrc522.uid.size; ++i) {
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    Serial.print(" ");
  }
  Serial.println();
}

void setup() {
  Serial.begin(9600);
  while (!Serial); // Wait for serial.
  SPI.begin();

  mfrc522.PCD_Init();
  Serial.println("Initialized...");

  // default access key STANDARD KEY 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
  for (int i = 0; i < 6; ++i) {
    key.keyByte[i] = 0xFF;
  }
}

void loop() {
  if ( ! mfrc522.PICC_IsNewCardPresent() ) {
      return;  // No card present, continue.
  }
  if ( ! mfrc522.PICC_ReadCardSerial() ) {
      // On success this function will return 1 and set the uid struct mfrc522.uid
      return;
  }

  printCardUid();

  // Write data to block.
//  writeBlock(15, writeBlockContent);
//  if ( readBlock(13, readBlockContent) == MFRC522::STATUS_OK )
//    printReadBlock();

  dumpCard();

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}

And I quote:

With each memory access the internal logic verifies the format of the access
  conditions. If it detects a format violation the whole sector is irreversibly blocked.

The only thing that can get you locked out of a sector is incorrectly formatted access bits. As long as you didn't touch those, the sector should still be accessible.
It looks like you tried to change key A and key B. With the transport config, the contents of the sector trailer can only be altered if you authenticate the sector with Key A. Is that what you did? Lets continue then. Since you left the access bits unchanged (right?), it means only key A has R/W access to all blocks (except the manufacturer's) and key B, since it's still readable, can be used to authenticate but can't be used to access blocks. So, if your key change was successful, then you should be able to access the sector with your new key A i.e. {0,0,0,0,0,0}. If it wasn't successful (maybe because authentication failed), then the default key A should still be valid.

I tried accessing with A but I still get timeout in communication. Here's what was before in the trailer block:

Block 11 0 0 0 0 0 0 FF 7 80 69 FF FF FF FF FF FF

I've tried login with both key A being {0,0,0,0,0,0} and {FF,FF,FF,FF,FA} but it doesn't work. I can read the other blocks using key A {FF, FF, FF, FF, FF, FF }

@Metonymy Have you tried using the default key A? Wheres the code you used to change the keys? Edit your post.

I've tried used the default key, I can only read the other sectors with it.


text:
Arduino code is not working for unipolar stepper motor
I am using unipolar 1.8 degree stepper motor. I have written code to rotate stepper motor i.e. when A0 pin becomes HIGH it should rotate in clockwise and when A1 pin becomes HIGH it should move anti clockwise but motor is rotating only once when I am making A0/A1 HIGH and then stops. After that it is not rotating even if i am making A0, A1 pin high. I am very new to this please tell how to solve this problem. I am using microstepping drive, nema 17 stepper motor and Arduino Uno board.
#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32

#define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
int  Steps2Take;
int buttonApin = A0;
int buttonBpin = A1;
int dirpin = 8;
int steppin = 9;
void setup()
{
  pinMode(buttonApin, INPUT);
  pinMode(buttonApin, INPUT);
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  small_stepper.setSpeed(1900);
}
void loop()
{
  int valA = digitalRead(buttonApin);

  if (valA == HIGH)
  { digitalWrite(dirpin, HIGH);
    for (int x = 0; x < 100; x++)
    { digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
    }
  }
  int valB = digitalRead(buttonBpin);

  if (valB == HIGH)
  {
    digitalWrite(dirpin, LOW);
    for (int x = 0; x < 100; x++)
    {
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
      digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
    }
  }
}

Split the problem up, check you button code is working by using them to light a LED.  Then get your motor spinning.  (Any reason why you are using the Analog Pins?)

I think yo need to read the buttons with analogRead() as you have connected them to A0 and A1 pins of arduino (A0 & A1 pins are analog ).

how many wires does the motor use?

your code looks like it is written to drive a regular motor

I have mentioned in the comments that you should read the buttons with analogRead(). But you can do it other way by simply connecting the button pin to digital inputs on arduino(any from 0-13). Analog pins are mostly used for accessing the sensor data as far as I know. I am correcting your code as below:
#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32

#define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
int  Steps2Take;
int buttonApin = 4; //connect button to digital pin 4 on arduino
int buttonBpin = 5; //connect button to digital pin 5 on arduino
int dirpin = 8;
int steppin = 9;
void setup()
{
  pinMode(buttonApin, INPUT);
  pinMode(buttonApin, INPUT);
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  small_stepper.setSpeed(1900);
}
void loop()
{
  int valA = digitalRead(buttonApin);

  if (valA == HIGH)
  { digitalWrite(dirpin, HIGH);
    for (int x = 0; x < 100; x++)
    { digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
    }
  }
  int valB = digitalRead(buttonBpin);

  if (valB == HIGH)
  {
    digitalWrite(dirpin, LOW);
    for (int x = 0; x < 100; x++)
    {
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
      digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
    }
  }
}


text:
Is it possible to have an Adafruit music maker shield and a sensor connected to the same Arduino?
Are the analog I/O pins on the Arduino still available for sensors when there is an Adafruit Music Maker shield attached to it? I want to play a sound file, but only when a PIR sensor senses motion.

What does the schematic and/or datasheet for the music maker say?

If you look at the PCB of the Adafruit Music Maker here:
https://learn.adafruit.com/assets/16643
You can see that there are no connections on the analog I/O of the Arduino.

Could you please expand your answer a bit? Actual pin numbers would be great.


text:
Python script to toggle LED's
I have 8 LED's connected to a shift register on my arduino uno r3. I am trying to write a Python3 script that will prompt a user to select one of the LED's and then prompt to toggle on or off.
Should be pretty basic but I cant seem to get this working.
I have already botched my code trying to get this running:
the jist of my python script is
import serial
import os
import time

os.system('clear')

ser = serial.Serial('/dev/cu.usbmodem1431', 9600)

while True:
    led = input("Which LED do you wish to operate? (press x to quit): ")

    if led >= '0' and led <= '7':
        print("Operating LED # %s" % led)
        ser.write(str.encode(led)) # sends the choice of led to arduino'
        on_or_off = input("Do you want to turn it on or off (press 0 for off and 1 for on): ")

        if on_or_off == '0':
            #send command to arduino to turn off the selected LED
            print("Command sent to arduino to turn OFF LED %s" % led)
            ser.write(str.encode(on_or_off))
        elif on_or_off == '1':
            #send command to arduino to turn on the selected LED
            print("Command sent to arduino to turn ON LED %s" % led)
            ser.write(str.encode(on_or_off))
        else:
            print("Please enter 0 or 1 to operate the LED. ")

    elif led == 'x':
        ser.close()
        break
    else:
        continue

For some reason Arduino is only dealing with the first input...
HEre is my loop code on the arduino
void loop() {
  if(Serial.available() > 0){
    led = Serial.read(); // from python script the led to operate
    led = led - '0';
    if(led >= '0' && led <= '7'){
      if(Serial.available() > 0){
        ledState = Serial.read(); // expects the led state next
        ledState = ledState - '0';
        if(ledState == '0'){
          shiftWrite(led,LOW);
        }else if(ledState == '1'){
          shiftWrite(led,HIGH);
        }
      }
    }
  }
}

shiftWrite is a function I wrote because there are 8 LEDS hooked to a shiftRegister
update:
I tried the state machine suggestion and it didnt work...
  void loop() {
  while(Serial.available()){
    led = Serial.read();
    led = led - '0';
    if(led>= 0 && led <= 7){
      state = 1; //We've received the LED # go to state 1
      Serial.println(led);
      Serial.println(state);
      Serial.println(ledState);
      continue;
    }
    if(state == 1){
      ledState = Serial.read();
      ledState = ledState - '0';
      if(ledState == '0'){
        shiftWrite(led,LOW);
      }else if(ledState == '1'){
        shiftWrite(led,HIGH);
      }
      state = 0; //Ended the operation return to state 0
    }
  }
}

With the serial monitor in the arduino IDE open (not running the python script) I tried this input: 4,1
This is my output on the serial monitor:
4
1
0
1
1
0

Any ideas? Basically the same problem as before...I actually thought the state machine idea would work...

You actually didn't follow exactly my solution, you're assuming that '0' is 0 and '1' is 1 while in fact, '0' = 48 and '1' = 49. You have to write if(ledState == 0) not '0'. same for '1'

I'll give that a shot

void loop() {
while(Serial.available()){
led = Serial.read();
led = led - '0';
if(led >= 0 && led <= 7){
state = 1; //We've received the LED # go to state 1
Serial.println(led);
}
if(state == 1){
ledState = Serial.read();
ledState = ledState - '0';
Serial.println(ledState);
if(ledState == 0){
shiftWrite(led,LOW);
}else if(ledState == 1){
shiftWrite(led,HIGH);
}
state = 0; //Ended the operation return to state 0
}
}
}

Entering 4 ... it outputs
4
-49
So it's somehow jumping and setting ledState before I enter anything.

I figured it out, check your Serial Monitor, you must set it to No Line Ending. There is nothing wrong with the code, it's just the Serial Monitor, when you press Enter, it sends another character which makes the loop go crazy.

It is set no line ending... I was only using the serial monitor to debug...pythons output is doing the same thing

Post your complete code not only the loop(). It actually worked for me.

Try this code, it is working as intended:
void setup() {
  Serial.begin(9600);
}

int state = 0;
int led;
int ledState;

void loop() {

  while (Serial.available())
  {
    if (state == 0)
    {

      led = Serial.read() - '0';
      if(led >= 0 && led <= 7)
      {
        state = 1;
        Serial.println("Got LED number: " + String(led));
        break;
      }
    }
    if (state == 1)
    {
        ledState = Serial.read() - '0';
        if(ledState == 0)
        {
          Serial.println("LED n " + String(led) + " is now OFF");
        }
        else if(ledState == 1)
        {
          Serial.println("LED n " + String(led) + " is now ON");
        }
        state = 0;
    }
  }

}

This makes sense. I haven't tried it against my python code...but breaking from the loop once the LED is chosen should fix my issue.  I will update you tomorrow if this works.

You're assuming that the microcontroller is going to wait until you choose LED state, which is wrong. Try this:
int state = 0;
int led;
int ledState;

void loop() {
  while (Serial.available())
  {
    if (state == 0)
    {
      led = Serial.read() - '0';
      if(led >= 0 && led <= 7)
      {
        state = 1; // Here we have got the LED number, go to state 1
        continue;
      }
    }
    if (state == 1)
    {
        ledState = Serial.read() - '0';
        if(ledState == 0)
        {
          shiftWrite(led,LOW);
        }
        else if(ledState == 1)
        {
          shiftWrite(led,HIGH);
        }
        state = 0; // Here we ended the operation, return back to state 0
    }
  }

}

You need what we call a state machine, here I use state=0 for the state corresponding to choosing LED number, state=1 is for the state that waits for the operation ON/OFF.

I tried that, but its still not working. To debug I've got the serial monitor on the arduino ide communicating...and printing out what the arduino is receiving... I'll post a response so you can see my code...

I've updated my post...so you can see the output and new code.


text:
Wire over 1ft does not work with sensors SRF02
Im using an SRf02 ultrasonic sensor, and I need to make the wires long to elevate the sensor. They turn on and blink and are able to transmit a signal, yet they are not able to receive a signal. What is the error?

Which interface are you using - UART or I2C?

im using i2c as the interface

I thought you might be. Are you using the internal pullups of the Arduino IO pins or have you added external pullup resistors?

internal, i havent added any resistors

Again, I suspected as much.

Using the internal pullup resistors for I2C is not recommended.  Arduino are very wrong in providing those as the default option and basically "hiding" the fact that I2C needs decent pullup resistors from you.
The internal pullup resistors, because they are so weak (i.e., a high resistance, typically > 50KΩ), do not pull the clock and data lines up adequately, and as such are only suitable for very short connections (in the order of a few inches).  Anything longer and the induced noise and inductance and capacitance of the wires will corrupt the I2C waveform.
I2C requires pullup resistors in the range of 2.2KΩ to 4.7KΩ.  As you can see that is more than 10x the pullup strength of the internal resistors.
For off-board connections (i.e., wires) you want the lower end of that range.  So add a 2.2KΩ resistor between SCL and +5V and another between SDA and +5V and you should find it works much better.

so what do you mean, add the resistor between SDL and V+, i cant just place it in between SDL on arduino and the TX pin of the sensor?

I mean exactly what I say. Connect a 2.2k resistor with one end connected to the SCL pin on the Arduino and the other end connected to +5V on the arduino. The same with the SDA pin.

i uploaded a picture in the original post, is this what you mean?

I don't know, it's too small to make out.

i put a better picture

It's confusing to work out what goes where in that picture, but I think you have it right, yes. It's not exactly a hard concept, there's only two ends to a resistor and I have told you the two places they connect to.

yeah i get what the circuit is supposed to look like, it didnt work btw


text:
Mini Arducam module camera shield - 2MP ov2640 interface with Arduino Uno
MINI ARDUCAM MODULE CAMERA SHIELD - 2MP OV2640
Arducam Multi-camera adapter board for Arduino SPI Mini Camera
I have the above two components with me along with ARDUINO UNO R3.
I want to stream video using these. ARDUCAM provides library for this.
ARDUCAM LIBRARY
ARDUCAM DATASHEET
When I have chosen example program ArduCAM_Shield_V2_Video_Streaming and tried uploading it to Arduino it showed no ArduCAM.h: No such file or directory.

I have downloaded the library and kept it in the libraries folder of ARDUINO.
Can someone help me out with this??

what's the picture with the horizontal orange bar? ... difficult to see

how are you going to stream video from the arduino?

did you install the library?

The error message in the image (”ArduCAM.h: no such file or directory”) can only mean that the library hasn’t been installed correctly.

As Nick Gammon wrote: There is no way, that you are sending video with an Uno. Its just not up to the task

https://www.youtube.com/watch?v=07UwmbeFCZQ

Please refer this YouTube Video

The Uno which you mention has 2 KB of RAM. 2 MP of data would be 2,000,000 x 3 bytes (red, green, and blue), in other words 6 MB.
The screenshot you showed seems to show that the library is designed to take a still photo and buffer it. As you might imagine, buffering 6 MB would take a while, especially as you can only fit 2 KB at a time.
You simply won't be streaming video using the Uno, so the error message is more-or-less irrelevant.
It might be relevant if you actually wanted to take single photos and send them.
In that case, you probably haven't installed the library properly.

https://www.youtube.com/watch?v=07UwmbeFCZQ

Please refer the YouTube Video above...

Yeah, OK. I can't see the resolution but that looks like a whole series of stills at about 1 frame per second. I suppose you can call that "streaming video" if you want to have a security camera taking photos of a room in your house. I assumed by "video" you meant what most people would call video, namely around 24 FPS or more.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
MCP23S17: Programming IODIRx-Register works in loop(), but not in setup()

I use a single MCP23S17 connected to an Arduino Uno. I use its port B for output and port A for input. When I first started to use this device I noticed, I could read pins, but using them as output failed. After a lot of debugging and trial and error I found out, that the IODIRx Register was never programmed. I then copied the respective code from the setup() routine — where it belongs IMHO — to the loop() routine.
And miraculously the IODIRx Register was written correctly. The code below contains the IODIRx programming snippet in the setup() as well as in loop(). But only in loop() it yields an effect. This means: The output will work only after the first traversal of loop() in my example.
The rest of the setup() routine obviously works, which means it is called at least. SPI is initialised correctly there.
This drives me nuts. What the hell is a setup routine for, if you can't setup things there. And why on earth doesn't it work then? I don't do strange things there.
#include <Arduino.h>
#include <Wire.h>
#include <inttypes.h>
#include <SPI.h>
#include "flanschcontrol.h"
#define DEBUGOUTPUT
#define PROTOV2
typedef int elem_type;
#define ADDRESS (0)
#define    OPCODEW       (0b01000000)  // Opcode for MCP23S17 with LSB (bit0) set to write (0), address OR'd in later, bits 1-3
#define    OPCODER       (0b01000001)  // Opcode for MCP23S17 with LSB (bit0) set to read (1), address OR'd in later, bits 1-3
#define    ADDR_ENABLE   (0b00001000)  // Configuration register for MCP23S17, the only thing we change is enabling hardware addressing
uint8_t PexSSPin=7;

void setup() {
   Serial.begin(9600);
    pinMode(PexSSPin, OUTPUT);
    SPI.begin();
    SPI.setClockDivider(2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);

    delay(1000);
    PORTD &= 0b01111111;    // Slaveselect low

    SPI.transfer(OPCODEW | (ADDRESS << 1));
    SPI.transfer(IODIRB);
    SPI.transfer(0b10101010);
    PORTD |= 0b10000000;    // Slaveselect high
    delay(1000);
}

void loop()
{
    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b00000000);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("0");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b11111111);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("ff");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b00001111);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("0f");
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));             // Send the MCP23S17 opcode, chip address, and write bit
    SPI.transfer(GPIOB);
    SPI.transfer(0b11110000);
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.println("f0");
    delay(1000);

    int value;

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODER | (ADDRESS << 1));  // Send the MCP23S17 opcode, chip address, and read bit
    SPI.transfer(GPIOA);                      // Send the register we want to read
    value = SPI.transfer(0x00);               // Send any byte, the function will return the read value (register address pointer will auto-increment after write)
    value |= (SPI.transfer(0x00) << 8);       // Read in the "high byte" (portB) and shift it up to the high location and merge with the "low byte"
    PORTD |= 0b10000000;    // Slaveselect high
    Serial.print("pindata: ");
    Serial.println(value);
    delay(1000);

    PORTD &= 0b01111111;    // Slaveselect low
    SPI.transfer(OPCODEW | (ADDRESS << 1));
    SPI.transfer(IODIRB);
    SPI.transfer(0b10101010);
    PORTD |= 0b10000000;    // Slaveselect high
}

Definitions of some preprocessor thingies:
#define    IODIRA    (0x00)      // MCP23x17 I/O Direction Register
#define    IODIRB    (0x01)      // 1 = Input (default), 0 = Output
#define    GPIOA     (0x12)      // MCP23x17 GPIO Port Register
#define    GPIOB     (0x13)      // Value on the Port - Writing Sets Bits in the Output Latch

Please show the declarations for IODIRB, GPIOA, GPIOB.

@NickGammon: I added the defines.

I have one question. Once you set the PinMode of an expander then can you change the mode without giving a reset? I mean, I have to use 3 expanders for controlling an SRAM: on one MCP I have the data lines, on the second one I have the control signals and on the last one I have the address lines. Firstly, I do a SRAM_WRITE, so I need the pins of the first expander to be OUTPUTs,then I do a READ_SRAM so a need the pins of the first expander to be INPUTs. Can I change the mode from output to input? Then I am trying to check the signals with an oscilloscope. When a do a pinMode OUTPUT of the expa

@Gabriele: Why should you have to do a reset to change pin behaviour? But please don't use the comment section to ask new questions.

You've fallen for the old "slave select pin is already low" trick!
Let me show you. First we add a line to bring pin 2 high before starting the sequence (for logic analyzer triggering):
pinMode (2, OUTPUT);     // <--- pin 2 output
delay(1000);
PORTD |= bit (2);        // <--- pin 2 HIGH
PORTD &= 0b01111111;     // Slaveselect low
SPI.transfer(OPCODEW | (ADDRESS << 1));
SPI.transfer(IODIRB);
SPI.transfer(0b10101010);
PORTD |= 0b10000000;    // Slaveselect high
delay(1000);

This is the logic analyzer output of running your sketch:

Notice how SS is low all the time, and thus the chip does not respond to the command?

Now we add a line before the SPI.begin
PORTD |= 0b10000000;    // Slaveselect high
SPI.begin();
SPI.setClockDivider(2);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);

Now look at the results:

This time you get the transition of SS from high to low, the chip notices it, and we have a valid SPI transaction.
So without bringing SS high, the first thing you sent was always going to fail.

It was nothing to do with it being in setup - it couldn't be. After all the logic is basically this:
init ();
setup ();
while (true)
  loop ();

Personally I wouldn't hard code all those bit patterns throughout the code. What if you change the slave select pin one day?
How about:
digitalWrite (PexSSPin, LOW);
/// write to chip
digitalWrite (PexSSPin, HIGH);

Isn't that much more readable? And easier to change later?

Hahahaaa, that's good. Works flawlessly now. My code looks so awful due to all the debugging steps I took. In the beginning it was a nice class with everything in it's place. Finally I unrolled all crucial parts into the main loop and used constants everywhere to rule out all other programming failures. Thanks for riddling this for me.


text:
pcDuino 3B Wire library errors
I recently purchased a pcDuino 3B and I am very pleased with the Board so far. I can use the preinstalled arduino IDE to program the board from the board and run programs.
However, when I came to use I2C, it generated a load of errors with the built-in libraries when I tried to compile. I don't know why it did this, it does it when trying to compile any program using I2C. Here is the error list (Yes, I am using an Adafruit display library that works fine with exactly the same sketch on my laptop):
In file included from /usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Stream.h:26:0,
                 from /usr/share/arduino/hardware/arduino/pcduino/libraries/Wire/Wire.h:9,
                 from Stopwatch_new.ino:1:
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Print.h:47:23: error: ‘byte’ has not been declared
In file included from Stopwatch_new.ino:1:0:
/usr/share/arduino/hardware/arduino/pcduino/libraries/Wire/Wire.h:41:23: error: ‘byte’ has not been declared
Stopwatch_new.ino:5:51: error: cannot allocate an object of abstract type ‘Adafruit_RGBLCDShield’
/home/ubuntu/Arduino/libraries/AdafruitLCD/Adafruit_RGBLCDShield.h:68:7: note:   because the following virtual functions are pure within ‘Adafruit_RGBLCDShield’:
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/Print.h:47:17: note:  virtual int Print::write(int)
Stopwatch_new.ino:5:23: error: cannot declare variable ‘lcd’ to be of abstract type ‘Adafruit_RGBLCDShield’
/home/ubuntu/Arduino/libraries/AdafruitLCD/Adafruit_RGBLCDShield.h:68:7: note:   since type ‘Adafruit_RGBLCDShield’ has pure virtual functions
Stopwatch_new.ino: In function ‘void updateScreen()’:
Stopwatch_new.ino:125:27: error: call of overloaded ‘String(float&, int)’ is ambiguous
Stopwatch_new.ino:125:27: note: candidates are:
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:44:14: note: String::String(unsigned int, unsigned char)
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:43:14: note: String::String(int, unsigned char)
/usr/share/arduino/hardware/arduino/pcduino/cores/arduino/WString.h:42:14: note: String::String(unsigned char, unsigned char)

It seems that no one else is having this issue.
Just to clarify, the issue is not with my code or the library, it compiles fine on my other computer running WINDOWS but same Arduino version (1.5.3), same sketch code and same library code.
Help much appreciated, thanks!

It turns out that the libraries for compiling were incomplete. Having copied the libraries for the official IDE, it worked fine.


text:
Following on ESP8266 Board pins, how do they map on the motor shield?
Here is the answer: All pins corresponding to the G row are connected to ground. All Pins corresponding to the V row are connected to NodeMCU's 3V3 pin.
D row pins tagged from 0 to 8 correspond to NodeMCU's D1-D8 pins. D row pins tagged with SD2, SD3 corresponds to NodeMCU's SD2, SD3 pin
UTART/SPI section:
Tags corresponding to the pins are self explanatory.
Near the white-colored power switch we have a pin called "AD". I couldn't figure how this motor shield's "AD" pin is interfaced to NodeMCU. Do you have any idea?
Following on Basic Question - ESP8266 Board Pins, I can't seem to map the pins on its motor shield to software (the ones named UART/SPI, the GPIOs and the Analog Inputs). See the third image, with a NodeMCU installed.

The GPIOs seem to conflict with the motors on Arduino, and I have no idea what to do here. Documentation is pretty much useless.

This question is about a ESP8266 and this is the Arduino SE forum, you might try the Electronics SE forum, there are more ESP8266 users over there so you will get a better/quicker answer.  Personally I would buzz them back to the socket for the NodeMCU and then use them from there

Hello @Matt , thanks for the answer, but the question is actually about the code, and how to map the code to the physical pins, that's why I posted it here. Sorry if it was the wrong place!

Which forum it should be depends if you are programing the ESP via the Arduino IDE or in LUA.  The same still hold true though, you need to know what pins the software needs to address, so you need to find out what pins on the board connect to your ESP.  Then you just need to use the correct constant.  So if GPIO_0  (Yellow box) connects to D0 on your breakout board then your code needs to refer to GPIO-16, Obs :)
Have you seen this before?https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=616

BTW Majenko is saying the same thing, hint hint.

You see the pins marked PWMA, PWMB, DA and DB? Those are the pins that control the motors (PWMx is the speed, Dx is the direction). Whatever pins on your ESP8266 board plug into those holes are the pins you need to use in your code. How those pins map to names and numbers in the Arduino API depends entirely on what the board is you're plugging in and what the author of the board definition files was thinking at the time.
In short, look at your board (which we cannot see) and see what GPIO pins are in the same location as the pins I pointed out. Then control those pins in your software.

thanks for your answer. As specified on the question, the board is a ESP8266, the NodeMCU. Actually, I was asking about the pins marked as SD2, SD3, and 0 to 8, with rows marked D, G and V. The ones that control the motors I managed to use.

@AlexandreStrube Then read the manual for the NodeMCU? That will tell you which pins on the ESP8266 module those pins (which are clearly labelled the same on the NodeMCU) are connected to.

@AlexandreStrube - You should have SD0 to SD3 on your NodeMCU (On the analog pin side) - They are normally controlled in the software by SDD0 to SDD3.  The 0 to 8 pins, well you have pins marked D0 to D8 and I am going to guess the on your motor shield they are connected to 0D to 8D, in software they are controlled by GPIO1 to GPIO16 - see the link in my comment above.  You can prove this by writing an app the lights an LED and toggling each of the pins high in sequence, or you could use a multimeter and buzz it out.  Once you know the physical connections working out the s/w should be easy.


text:
Understanding Nikon modified version of SPI
I am trying to use this library to connect a Nikon lens to an Arduino.
https://lainy.github.io/NikonLens/classlain_1_1t_nikon_lens.html
I'm finding it very hard to understand the correct wiring.

Connections are as follows (with Arduino Uno pin numbers):
SS (10) is unused.
SCK (13) is connected directly to lens SCLK.
MISO (12) is connected to the lens Data line, which must be pulled
  high.
MOSI (11) drives the lens Data line through a transistor,
  open-collector. So: MOSI -> Base, Data -> Collector, GND -> Emitter
handshakePin_In is connected directly to lens H/S
handshakePin_Out drives lens H/S through a transistor, open-collector.

I would like help to understand this.

drives the lens Data line through a transistor, open-collector. So:
  MOSI -> Base, Data -> Collector, GND -> Emitter

It uses a variant of SPI interface. I'm just finding it hard to wrap my mind around it.

It is simply a way of splitting a single-pin read/write function between two pins. It's easier to visualise with schematics:

simulate this circuit – Schematic created using CircuitLab
Under idle conditions the resistor pulls the data signal high. When the lens wants to transmit the open-collector output (represented by a transistor here) either pulls the data line low (for a 0) or releases it to be pulled up by the resistor (for a 1).
The Arduino reads that data in through the data in pin.
When the Arduino wants to transmit it does the same thing, but the "open collector" is external in the form of the transistor. It drives the transistor using the data output pin to get it to pull the data line low for a 0, or release it to be pulled up by the resistor for a 1.
This is exactly the same way (on an electrical level) that I2C works and studying that protocol can help you to understand what is going on here.

great answer! Can you describe how the correct wiring would look like for interfacing Arduino with a Nikon camera? I.e. Arduino with MISO and MOSI pins acting as an SPI slave and Nikon camera with a single data pin as master?

authors: Александр Иванов


text:
Getting negative results from calculations
I'm trying to proportion potentiometer value to analog pin value. Like 1024 to 255.
int readVolumePot() {
    int val = analogRead(potVolumePIN);

    Serial.print("VOL");
      Serial.println((val * 255/1024));

      return (val * 255/1024);
  }

As potentiometer turns I got irrelevant values.
VOL3
VOL3
VOL3
VOL17
VOL-16
VOL-16
VOL-21
VOL-1
VOL-10
VOL-3
VOL-4
VOL11
VOL8
VOL13
VOL17
VOL15

In Arduino's website they say

some constant calculations may overflow (e.g. 60 * 1000 will yield a
  negative result).

Notwithstanding, I cannot find an appropriate way to convert the potentiometer value to analog pin value.

Try using map().

a more elaborate answer here

analogRead() returns a number from 0 to 1023, and you want to convert that to a range from 0 to 255? One easy way would be to simply divide the reading by 4.
On a more general note, given that the numbers will (should!) never be negative, there's a flavour of int called unsigned int. By using that:
unsigned int val = analogRead(...);

you can cover a range from 0 to 65535 instead of int's -32768 to 32767. That will give you a little more head room - but not enough to multiply the maximum value 1023 by 255 first.
There's also another type long. That covers the range from -2 to 2 billion (and a bit), while unsigned long goes from 0 to 4 billion (and a bit) - but that uses a LOT of processing for the poor Arduino to work with.

A nice feature of unsigned ints: if val is unsigned, then val / 4 is optimized by the compiler into a bit shift, much more efficient than the actual division you would get if val was signed.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Record a duration of time as data
I have very little experience with the Arduino and am hoping that you may provide me with some helpful info.
I would like to build a device that records time spent on a project.  I envision the main Uno with a switch, microSD breakout, and an LED to indicate its tracking your time. When setup the user could simply press the switch/button (light up the LED to show you're "working") and while you plug away on your day job the Uno will track the time between switch on and switch off. Then at the time the switch is turned off, have the Uno write a simple data file containing the total time spent on that activity.
I have a basic idea of what I need hardware wise, but am hoping to find insight to the backbone of software programming to make something like this begin to take shape.

Use an RTC and record a start time and an end time (timestamp) for each job. This will give better quality raw data that is easy to use, and flexible, for calculations and reporting.

If you can live with an accuracy of only ~ 0.5%, then you don't need an RTC, millis() is fine. For more precise timekeeping, you do want the RTC.

There are two ways of doing this:

Using a Real Time Clock (RTC) chip, which you connect to your Arduino.
Using the millis() function of the Arduino.

Needless to say, they aren't completely the same in efficiency. An RTC is a dedicated chip for measuring time and is incredibly accurate. The millis() is not as accurate, but still pretty accurate.
So, it really depends on how accurate you want it to be. You can make millis() more accurate through code, which isn't something difficult. But an RTC always works fine and is always more accurate, if only by milliseconds. In general: need to time long durations, an RCT is probably better.
Regardless of the method you will use, you can convert the data into the desired format so it can be read easily when looking at the files on the SD card. So, for example: you can write code that simply checks how many hours fit in the saved time data, and after that you can check the minutes and even after that you can check for the last seconds. For this you're going to need modulo.
Here are some resources you might want to check out:

An Arduino tutorial for an RTC chip: http://playground.arduino.cc/Main/DS1302
Official documentation on millis(): https://www.arduino.cc/en/Reference/Millis

Your link about millis() inaccuracy is way out of date. The 9.54 hours rollover issue was solved in 2008.

Well, good to know because that basically means millis() is almost as accurate as an RTC without needing to correct it with code.

That depends on the Arduino. Many of them, like the Uno, are clocked off a ceramic resonator, not nearly as accurate as the quartz you have in a typical RTC.

Yep. So if OP is going to be using it for long periods of time, he's definitely better off using an RTC.

Thank you guys, this is all very helpful!! I don't need extreme accuracy for this application - only looking to deal in nearest tenths of an hour (0.1 or every six minutes) so the millis will probably work for me.  Happy to hear its nearly as simple as my brain is saying it should be :)

An RTC is a dedicated chip for measuring time and is incredibly accurate.

its accuracy will depend on the crystals used.  a temperature controlled one will be very accurate. But a regular one will just be as accurate as the crystal used, like a mcu.

The millis() is not as accurate, but still pretty accurate.

stock millis() undercounts. however, that undercounting can be mitigated via code. for long durations, the undercounting can be practically (but not completely) eliminated.

“stock millis() undercounts”. Do you have some evidence to back this?


text:
Help understanding how avrdude works with ArduinoISP and why its not working for me
I am trying to use avrdude with a Mega2560 running ArduinoISP
Note: I have the 10uF cap on the Mega2560 RESET line as described by Ardunio.
Also, I am using avrdude/6.3 on Windows 10.  The Mega2560(ArduinoISP) is connected to the PC using an a USB cable - connection is COM8.
I have a couple of tasks I want to do

Update the firmware on my USBASP
Load Arduino boot on ATTINY85 dev board.

I started with Arduino IDE but moved to avrdude to better understand the problem
For #1:
Wired it per https://www.arduino.cc/en/Tutorial/ArduinoISP
AVR-ISP pin     MEGA-ISP pin
6/10 (name)

1/9 (MISO)      50
2/2 (VCC)       VCC
3/7 (SCK)       52
4/1 (MOSI)      51
5/5 (RESET)     53
6/10 (GND)      GND

I tried using the command:
avrdude -c arduino -p m8 -P COM8

I get the error
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xed
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

avrdude done.  Thank you.

--UPDATE-- The error above was caused by not setting the BAUD rate. Now I get:
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.

What I really want to know is more of how this process works so I can better understand it and be able to debug the issues.

Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?
What does "stk500" mean?  Is that the programming protocol, the ISP protocol, or something all together different?
Is this all documented somewhere?

baud rate, fuses? use IDE to burn the botloader

I get similar errors when I try to use the IDE (which I believe uses avrdude in the bacground.  That is why I am focused on understanding avrdude.  Note: I normally use the IDE but not with a ISP.

Please add info about the wiring.

Added wiring info

programmer is not responding seems to show the problem is with the programmer, not the target. 2. stk500 is the protocol the Arduino uses to program itself. I don't think this should be the protocol to use when using the Arduino-as-ISP, but it's been a while. 3. Not really. All the info is out there, but not in one place.

I think -c arduino should be -c avrisp -b 19200

@Gerben baud rate appear to have been what was causing the 'not responding'.  It now responds but I get 'Invalid device signature'.

What signature do you get?

the command for Uno as target and "Arduino as ISP" is avrdude -C avrdude.conf -v -patmega328p -cstk500v1 -P/dev/ttyACM0 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m as you can see in IDE console when you use "Burn bootloader"

@Juraj That is pretty much the same as what I am using but 1)my target is different, and I am no writing of fuses and  lock

@Gerben 'avrdude: Device signature = 0x000000'

@MikaelPatel I added detail on the wiring to the OP

@Gerben Re:Not really. All the info is out there, but not in one place  I am finding some stuff and collecting it and will add it as a Answer so it can at least be in this one place.

the Arduino as ISP page doesn't show wiring for USBASP or ATiny

@Juraj Arduino ISP page shows the pin numbers on each ISP board type by AVR-ISP signal name.  I just connect those to the same signal name on the target (USPASP/ATTINY).  For one example (USPASP) I added the specific connections.

Device signature = 0x000000' means it can't see/communicate with the target.

You have the use the correct reset pin on the USBasp. You can't use the 'reset' pin on the programming header on the USBasp, as that's is just a GPIO output pin on the ATMega8. It seems that some of the board have a jumper to connect this pin to the reset on the ATMeag8. Not properly resetting the target could give you the incorrect signature error.

The target board was not reset.
The "Arduino as ISP" sketch uses pin 10 to reset the target, not the SS pin. So even on Mega, wire reset of target to pin 10, not to pin 53.

Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?

the first error "not in sync" is a problem with communication with the programmer. it was caused by wrong baud rate. the "invalid signature" is a response from the programmer about target. if the signature could be read avrdude would print the target MCU type. all zeros signature is when the target doesn't answer. so check the wiring.

What does "stk500" mean? Is that the programming protocol, the ISP protocol, or something all together different?

yes it is a ISP programming protocol. the "Arduino as ISP" implements only this protocol

Is this all documented somewhere?

this is AVR MCU world, not Arduino. you can google avrdude reference, stk500 reference etc

This got it working.  How did you know it was the reset?

I use "Arduino as ISP" quite often. You could accept the answer to mark the question solved

Just recall that the question was not just to solve the immediate issue; but, to know how to trace the symptoms to the cause.  If you can add how the symptoms pointed you to the RESET connection then that would be a more complete answer.  Also I need to test it with the other test case.

the "check the wiring" rule. I enhanced the answer


text:
Can an IC be programmed by an Arduino and then be removed, to be used in an external breadboard?
I wanted to find out if is possible to write programs into a micro controller using the Arduino and use the micro controller independent of the Arduino board?

yes ...........

Yes. The compiles code will is burned in the Arduino ROM. You can then take the Atmel chip (the Arduino microprocessor) and use it. You only need a few extra component for a chip like the 328p (Arduino Uno).

That design also needs 0.1uF caps from the VCC, AVCC, and Aref pins to Gnd.

For another example, using another method, an Uno can program another MCU without the target needing any bootloader, thus enabling your code to occupy the entire Flash memory of the target devices. Here is a link describing how to program an Attiny using an Uno and the ArduinoISP example program. An Attiny85, for example, has 8K of flash, all of which is usable by your application, using this technique. For comparison, a bootloader in an Attiny85 takes about 2.5K, or 30% of the Flash space! And it only gets worse with the smaller Attinys.


text:
Stepper Motor won't reverse/turn CCW
Before bothering anybody, I've been Googling this issue for the last three weeks and have not been able to solve the issue, so must reach out for help.
My son has done multiple Arduino projects after having a Creation Crate subscription, and now we're working on a project together.  We bought a 28BYJ-48 stepper with driver, and figured it'd be just a question of copy-and-paste coding and we'd be in business.
I've tried the Arduino library, the AccelStepper library, countless other sketches from various websites and for some reason the stepper only vibrates when it's supposed to turn CCW.  There was one sketch we were using that used Serial Monitor to enter in the number of steps, and when i'd do a minus number of steps, it'd go CCW, but the next day no longer would!  I thought this was a motor or driver issue, but we've bought three more motor/drivers and still have the same problem.  In researching an answer, I've seen some people say to switch IN 3 & 4 but I still get same results.
We've been connecting 8 to IN1, 9 to IN2, 10 to IN3 and 11 to IN4.  Using a separate 5V power supply to the driver which is also grounded to the Arduino (have tried both ground pins just in case that makes a difference, but no).  We've also tried changing for another Arduino and this hasn't made a difference either.
we've tried multiple sketches from multiple sources, here's one as an example:
#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);

  // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

The Serial Monitor will state that it's turning CCW, but it isn't.  Any help would be much appreciated!  What we thought would be a simple step in our project has become a major roadblock!

which driver are you using?

one of the problems lies here figured it'd be just a question of copy-and-paste coding ..... the only time you should be copy-pasting is when you truly understand the code that you are copying and you are 100% sure that there are no errors .............. maybe you can start by activating the stepper motor windings one after another using digitalWrite()with a 1 second pause between steps .... that should make the motor move between steps

this appears to address your issue https://www.instructables.com/id/BYJ48-Stepper-Motor/

I'm using a ULN2003 driver board, thanks!

then look at the instructables.com page

I can confirm that it works witch switched wires, 2,4,3,5 worked for me.

I had this issue myself, when I tried to use these stepper motors (which are to be honest really crappy ones, but very cheap). Vibrating mostly means, that the phases of the motor are not activated in the correct order. These motors seem to work with an activation pattern for half steps (I don't know, if the motor is really doing half steps with this, because I didn't counted them for a whole revolution. But at least they worked). The Stepper library (I assume from your code, that you are using this one) isn't meant for this driver, so it will turn on the phases in a wrong order and always two phases at the same time (as for full steps).
I had success, when driving the 4 phases of the driver with the following pattern (for half steps):
1000
1100
0100
0110
0010
0011
0001
1001

I also found hints on the web (on a german site, just for reference, if you can read german), that - despite being meant for half steps - you can drive the motor with full steps with the Stepper library as well. You would have to change the order of pins in the definition of the stepper:
Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

This assumes the wiring as: D8->IN1, D9->IN2, D10->IN3, D11->IN4. Note, that using full steps means 2048 steps per revolution.

I also found a library specific for this stepper motor, but I haven't tested it: Stepper_28BYJ_48

Now you can decide yourself, which way you want to go. I personally would go for the full steps with the official Arduino Stepper library.

About the number of steps per revolution: I don't know, why the stepper doesn't work with a vale of 2048. But since the library only uses this to wrap up the correct phases for the revolutions, you can use a lower value, that is dividable by 4. For example 32, which is the number of full steps per revolution of the actual motor (it is attached to gears with a factor of 64). That should work.

Thanks for the input- indeed changing the pin order to 8,10,9,11 did the trick.  Oddly enough however, when I change variable for the steps per revolution from 200 to 2048 (the true number of steps in one revolution for this motor), it chokes and won't turn at all.  200 only turns it about a tenth of a rotation.  I've played with this variable and can change it amp to 660 (about a quarter turn), but any number higher than this and the stepper won't turn at all.  Any thoughts appreciated!

@Matt I edited by answer and added my thoughts about this. I hope, that helps.

Changing the pattern to 8x half-steps did the trick. Thanks!

https://forum.arduino.cc/index.php?topic=549927.0
This guy just flipped IN2 and IN3 and it solved the problem of going forwards and backwards. It worked for me and here is the code.
#include <Stepper.h> // Include the header file

// change this to the number of steps on your motor
#define STEPS 64

// create an instance of the stepper class using the steps and pins
Stepper stepper(STEPS, 8, 10, 9, 11);

int Pval = 0;
int potVal = 0;

void setup() {
  Serial.begin(9600);
  stepper.setSpeed(200);
}

void loop() {

potVal = map(analogRead(A0),0,1024,0,100);
if (potVal>Pval)
  stepper.step(10);
if (potVal<Pval)
  stepper.step(-10);

Pval = potVal;

Serial.println(Pval); //for debugging
}


text:
Using mills() in place of delay() on relays not getting solid switch over
I know I should post some code that maybe cleaner but really I am just in need of a answer to a problem I seem to run into a lot when using mills() in place of delay(), whilst making a Christmas light display.
Maybe it's me but I do not get contestant switching over of mechanical relays when I try to use mills() timing to switch relays . I seems like the code trips the relay then untrips the relay in milliseconds and not really latching the relay like I get with delay(). Is this the nature of the mills() choice where the output is triggered every cycle  but is not truly an output during the whole process cycle?  Now if this is true, then is there a good way to latch a relay with out using a delay()?
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
//

  unsigned long currentMillis = millis();
  unsigned long previousMillis = millis();
  int interval_on = 2000; //  Length of time On

  unsigned long currentMillis_off = millis();
  unsigned long previousMillis_off ;
  int interval_off = 2000; // length of time off

//
#define button 4
int Lite_1=0;

RF24 radio(7, 8); // CE, CSN

const byte address[6] = "00001";
boolean buttonState = 0;

unsigned long time;

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  Serial.begin(9600);
}

void loop() {
  unsigned long currentMillis = millis();        // must be in loop
   unsigned long currentMillis_off = millis();  // Must be in loop
  //                             const char text[] = "Hello World";
 //                       radio.write(&text, sizeof(text));
  //delay(1000);

   //                       delay(5); Removed to help in timing
   //                       radio.stopListening(); removeded to help in timing
   // Lite_1 = 1;
    radio.write(&Lite_1, sizeof(Lite_1));
  //    delay(1000);
 //   Lite_1 = 0 ;
 // radio.write(&Lite_1, sizeof(Lite_1));
  // delay(250);

  if (Lite_1 == 0 && currentMillis - previousMillis > interval_off)
    {
    previousMillis = currentMillis;
    previousMillis + 10;
    previousMillis_off = currentMillis_off  ;
    Lite_1 = 1;
    Serial.println(currentMillis);    //prints time since program started
      }
    //Debug
  // Serial.print("Time: ");
 // time = millis();

 // Serial.println(time);    //prints time since program started
//  Serial.println(currentMillis);    //prints time since program started
//  Serial.println(previousMillis);    //prints time since program started
//  Serial.println(previousMillis_off);    //prints time since program started
 // Serial.println(currentMillis_off);    //prints time since program started
  //delay(250);

    if (Lite_1==1 && currentMillis_off - previousMillis_off > interval_on)
       {
    previousMillis_off = currentMillis_off;
    previousMillis = currentMillis;
    previousMillis + 10;
    Lite_1 = 0;
    Serial.print("OFF: ");
    Serial.println(previousMillis_off);    //prints time since program started
    }

  }

Format your code correctly by editing your question,selecting the code and click the {} button in the editors toolbar or press Ctrl+k on the keyboard.

At which part of the code do you switch the relays? I don't see any digitalWrite() or similar, which could be used to switch something. Only Serial output.

What should it do? Is it to turn on the relay half a second with 2 seconds in between? Is that continuous or is that triggered by an event? Please add the extra information to your question.

Ron, you can't answer comments until you register to SE. Check your email.

Can you explain the role of nrf24L01 in this code?  There may be other ways to achieve the functionality that you need.

"role of nrf24L01"  is a Wifi  device  code  as I under stand it.

The program opens a Network connecition to another arauduino on the network

No digital write since it is just telling the other arduino to do the digirtal Write function at Lite_1 = 1

Something like this works.
  unsigned long currentMillis;
  unsigned long previousMillis;
  unsigned long nextEventTime;

  unsigned long interval_on  = 2000;        // length of time On
  unsigned long interval_off = 2000;        // length of time off

  bool Lite_1;

  void setup() {

    previousMillis = millis();

    Lite_1 = false;                                     // start at the begining of the off cycle
    nextEventTime = previousMillis + interval_off;      // start at the begining of the off cycle

    Serial.begin(9600);
    Serial.print("starting in OFF cycle\t");
    Serial.println(previousMillis);
  }

  void loop() {

    if (millis() > nextEventTime) {                     // check the interval before doing any other checks

    currentMillis = millis();

    if (Lite_1) {

      nextEventTime = currentMillis + interval_off;     // do the calculation only once
      Serial.print("OFF:\t");

    } else {

      nextEventTime = currentMillis + interval_on;
      Serial.print("ON:\t");
    }

    Lite_1 = !Lite_1;                           // invert value
    Serial.println(currentMillis);              // prints time since program started
    }
  }

When a value is added to a value from millis, and then compared to millis, that causes a rollover problem. Always subtract a previous millis from the current millis.

Then how would I do this math if I can not add to the Millis()?

I believe the way to make that work is nextEventTime - currentMillis > interval_of.  Informally speaking, doing that subtraction instead of an addition guarantees that we are going to be doing the inequality with a small number, rather than a number that's potentially large enough to roll over when interval_off is added to it.

Firstly, what is the purpose of declaring all variables as global ones? Secondly, if (millis() > nextEventTime) - this will not work properly around the moment of millis() rollover.


text:
What's taking up so much RAM in an almost empty sketch?
I wanted to check how much memory (RAM) is used by an "empty" sketch. Here is my code:
int freeRam()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

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

void loop()
{
}

My result was that I have 1839 bytes of free RAM. I have an Arduino UNO, so there are 2048 bytes of RAM in total. Which means that 209 bytes are already taken. Wait, 209 bytes?! I started thinking and figured out that the Serial buffer must take some space. I've opened HardwareSerial.h and found this:
#if (RAMEND < 1000)
  #define SERIAL_BUFFER_SIZE 16
#else
  #define SERIAL_BUFFER_SIZE 64
#endif

I've changed SERIAL_BUFFER_SIZE to 16 to see what will happen. (I've tried decreasing it to 1, but then the serial communication didn't work properly and I wasn't able to display the amount of free RAM). After this modification my result is 1935. So now "only" 113 bytes are taken. But what is taking this memory? HardwareSerial has 2 buffers:
struct ring_buffer
{
  unsigned char buffer[SERIAL_BUFFER_SIZE];
  volatile unsigned int head;
  volatile unsigned int tail;
};

ring_buffer rx_buffer = { { 0 }, 0, 0};
ring_buffer tx_buffer = { { 0 }, 0, 0};

So when the SERIAL_BUFFER_SIZE is 16 they take exactly 40 bytes. What is taking the remaining bytes (113-40= 73 bytes)? I'm aware that stack frames take some memory - calling main() which calls setup() whichs calls freeRam() probably take a few bytes, but 73 still seems too much.

what version of arduino are you compiling this on?

my version is 1.0.6

First off, a sketch that uses Serial cannot really be considered an empty sketch as Serial drags along a lot of function definitions, at least one Serial class instance (more on Arduino Mega, for instance), plus probably some more global variables...
sizeof Serial may be interesting to display as Serial is not limited to the TX and RX buffers, as you seem to believe. Its class also has a couple of additional data members on its own, plus members inherited from its superclasses, Stream and Print.
In addition, the Arduino IDE comes with the various "utilities" which you normally can't get rid of, like the millisecond timer that uses at least 9 bytes (see reference in wiring.c file).
So in the end, even an empty sketch (even without Serial) takes some SRAM space for global variables.
I think there is some way, with avr-size, to check out, with fine details, the size of data (not accounting for the runtime stack) after the sketch has been fully built.
Arduino IDE already displays some of this static memory information (at the end of "verification").
For example, on my IDE (1.5.8) for Arduino UNO, a really empty sketch, once compiled is mentioned to use 9 bytes of SRAM. Actually those 9 bytes are for 3 global variables, used by the millisecond timer. This number, of course, does not account for runtime memory usage, in particular the stack.
Then, just adding Serial.begin(9600); makes it use 182 bytes (ie 173 more bytes than an empty sketch). So you get the culprit.

I investigated this at some length a while back. On this page about putting constant data into program memory I obsessively tracked down every last byte of memory used in a small sketch. This was the sketch:
#include "memdebug.h"

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.print (F("Free memory = "));
  Serial.println (getFreeMemory ());
  }  // end of setup

void loop () { }

memdebug.h came from Andy Brown - Debugging AVR dynamic memory allocation.
That particular sketch actually used even more RAM:
Free memory = 1702

So where did the 346 bytes go? Here:

34 bytes for the HardwareSerial instance (Serial)

64 bytes for the Serial transmit buffer

64 bytes for the Serial receive buffer

4 bytes for the Serial transmit buffer head and tail pointers

4 bytes for the Serial receive buffer head and tail pointers

9 bytes for keeping track of millis / micros

4 bytes for memory allocation (__malloc_heap_start, __malloc_margin)

128 bytes for the heap safety margin

6 bytes for a few nested function calls (main -> setup -> getFreeMemory)

16 bytes for the compiler vtable for HardwareSerial

4 bytes for variables __brkval and __flp (used in memdebug)

2 bytes pushed onto the stack in main (to save registers)

2 bytes pushed onto the stack in setup (to save registers)

4 bytes pushed onto the stack in getFreeMemory (to save registers)

1 byte because the stack pointer starts at 0x8FF rather than 0x900
(That's 346 bytes accounted for)

What's a heap safety margin?

The heap and the stack grow towards each other (in opposite directions, one up, one down). Without a safety margin it would be possible to allocate room on the heap, with little or no "spare", and then crash soon afterwards when you call a function. Calling functions uses the stack, which would then encroach into the heap. Effectively the heap would get corrupted, if the stack didn't first (for example if you wrote to the memory in the heap, in the function you called). The heap safety margin gives a buffer zone to (try to) prevent that.