text:
"tamper" circuit of a reed switch: can I connect the two wires to an INPUT and an OUTPUT pin?
While working for the automation side of my new house, I'm currently in the process of installing several reed switches on top of external doors and windows.
Even if this could be used as a "security" infrastructure, I'm more interested, at the moment, at the "automation" side (checking the status of door and windows without the need to physically watch them) and as such, I'm going to extend the arduino-based infrastructure I've already planned and prototyped [more details here].
This is the reed-switch I've installed (1€ coin added for size reference):

and this is the related circuits:

As you can see, it comes with two circuits: one related to the "switch" funcionality; another one as a safety-measure to catch some "cuts" along the wires.
To check its status, currently, I've configured:

"contact circuit":

one end to an Arduino GROUND_PIN;
the other end to Digital PIN 52 (REED1_SW_Pin);

"tamper circuit":

one end to an Arduino GROUND_PIN (same GND pin as above);
the other end to Digital PIN 50 (REED1_AT_Pin);

Arduino setup:

pinMode(REED1_SW_Pin, INPUT_PULLUP)
pinMode(REED1_AT_Pin, INPUT_PULLUP)

Arduino code:

the main code-block handling REED events is reported below

Even tough everything is working fine, I wonder if there are better approaches, expecially inchecking the status of door and windows without the need to physically watch them terms of POWER-CONSUMPTION. So, here are my questions:

TAMPER-Circuit: due to its nature, it will always be a "closed" circuit, with current flowing inside, from REED1_AT_Pin to GND. Currently I'm checking its state every 1 second (#define REED_AT_CHECKDELAY   1000) but a frequency of once every 5 seconds, or even 10 seconds would be acceptable (for me). So I would like to have the current flowing ONLY during the "checking-timeframe". Something like:

every 5 seconds...
power-up something, getting the current flowing along the circuit;
check if the current flows;
if yes => OK
if no => set/keep the ALARM state
power-down the "something"

Is it feasible? If yes, how? Also: is it worth the effort?

REED-switch circuit: same as above. Polling approach is still acceptable (for me) but frequency need to be relatively high (5 seconds max), in order to keep of sort of "near-real-time feedback" when opening/closing windows. Best would be 2 secs polling-interval.
With such a timing, does the polling-approach make sense?
from an "electronic" point of view, what is the "to-be-preferred-scenario" for the Arduino board:

having a small, fixed, steady current, flowing out from a PIN, for YEARS on a 24/7/365 basis or...
having a continuosly transition from LOW->HIGH->LOW for a Digital PIN, say once every 5 seconds, again, for YEARS?

Every comment, sidenotes, hints, critics, whatever... is REALLY welcomed/appreciated.

Arduino code-block handling REED events
BTW: the full-code, where the REED switch is handled togheter with pushbuttons and relays, it's available on GitHub

    [...]
    if (reed_sw1_state != reed_sw1_previous_state) {
        // a change occurred. Are we in a "boucing" window?
        if (millis() - last_reed_sw1_debounce > REED_DEBOUNCE) {
          // no. So it's a real change
          // Let's handle the event...
          Serial.print(millis());
          Serial.print("[REED] - SW1 state CHANGED from [");
          Serial.print(reed_sw1_previous_state);
          Serial.print("] to [");
          Serial.print(reed_sw1_state);
          Serial.println("]");
          reed_sw1_previous_state = reed_sw1_state;
          last_reed_sw1_debounce = millis();
        } else {
          // yes. Let's ignore it
        }
      }

      // Let's check REED Switches anti-tamper state
      if (millis()-reed_at1_lastcheck > REED_AT_CHECKDELAY) {
         reed_at1_state = ! digitalRead(REED1_AT_Pin);
         if (reed_at1_state == HIGH ) {
            Serial.print(millis());
            Serial.print("[REED] - AT1 state OK [");
            Serial.print(reed_at1_state);
            Serial.println("]");
         } else {
            Serial.print(millis());
            Serial.print("[REED] - AT1 state ALARM - OnGoing TAMPER!!! [");
            Serial.print(reed_at1_state);
            Serial.println("]");
         }
         reed_at1_lastcheck = millis();
      }
      [...]

So I would like to have the current flowing ONLY during the "checking-timeframe".

Turn off the pull-up until just before checking. Allow a few milliseconds for the pull-up to raise the voltage.

With such a timing, does the polling-approach make sense?

Certainly, if you are trying to save battery power.

Bear in mind the voltage drops over long cable runs (and also possibly induced spikes). You might want a more powerful pull-up (eg. 10k) rather than the inbuilt 50k. You can still organize that by having an output pin turn on the voltage to the pull-up. Or, have the pull-up wired in permanently but instead of running the other side to ground, set the "ground" wire to OUTPUT and write LOW to it - and then set it to INPUT when you want it to be inactive.
See my post about Power saving - you could use a watchdog timer to wake the device at (say) every 4 seconds, to check things.
You may want to add in input-circuit protection (eg. a couple of diodes) to dampen down any incoming spikes. Even something simple like this:


text:
Detaching interrupts
I am using the following code to enable an interrupt for a pin:
*digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group

But I can't disable it. I am trying with this code:
if (*digitalPinToPCMSK(pin) == 0)
*digitalPinToPCICR(pin) &= ~(1<<digitalPinToPCICRbit(pin));

but it isn't working.

What pin is it? Why not use attachInterrupt and detachInterrupt?

The code is inside a function. attachInterrupt only works for two pins.

Don't you mean:
  PCICR  &= ~bit (digitalPinToPCICRbit(pin));

source: Stack Exchange

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

sort: votes


text:
How can I get my Arduino to recognize a specific object using some kind of sensor?
This is my first question on this site, and I'm relatively new with Arduino. I do have some experience using the board to reprogram a robot that used infrared proximity sensors, servos, and switches.
I would like to add a sensor on to the robot that will allow him to recognize specific "obstacles" that I will put in his environment (not walls!) For instance, when he sees a red card, he needs to spin, but when he sees a green card, he needs to roll in the opposite direction. I do not want to spend much on the cards, but I would be willing to put a small battery and LED in them if I had to. The cards do not necessarily need to be colored, I was just using that as an example.
The robot will be in a well-lit room with noise in the background. He will be controlled by an Arduino Uno, an infrared sensor and a remote control. He can be pretty close to the cards if he has to (3 centimeters or so would be enough). It would be ideal if he could discern different types of cards, but that is not necessary as long as he's able to tell a card from the rest of his environment.
I am simply not sure how to go about implementing this. I have read about using photoresistors to differentiate color, and they're really cheap, but will they be accurate enough from a distance? This is the light sensor I was considering using:
http://www.mouser.com/ProductDetail/Adafruit/161/?qs=GURawfaeGuDpQ5XPTNqKUw%3D%3D&gclid=Cj0KEQiA6IC2BRDcjPrjm_istoUBEiQASrLz1rQNwZgntUcccnOmrFph-pCbu60R00GNozB_XbZxYz0aAn0j8P8HAQ
I'm willing to pay about 5$ for one if I need to.
If I use the light sensor method, can I just use brightly colored cards or will I need to use LEDs? Is there a better way to accomplish my goal that you are aware of?
Thank you for your time. If there is missing information in my question, please tell me and I will add it.

How about NFC RFID cards?

I'm not sure. Your mentioning it was the first time I'd actually heard about the things. They sound really neat, but it looks like it'll cost about 45$ for the setup, and for that money I can get a nice color sensor and the cards will be easier to make. Thank you for your response, though, and I will keep it in mind!

A cheap RFID sensor is a few pounds plus the stickers, they're like 0.1-0.2 pounds usually (depends on the quantity) I think you'd get like 100 stickers plus a reader for 25 pounds. Plus RFID is much more reliable.

If you are controlling your robot with a remote control, why do you need it to detect cards, instead you can tell it to do whatever you want right?
If you want to detect specific objects according to their colors, arduino is not a platform i will choose, because it doesn't have processing power to do image processing.
But take a look at this, http://charmedlabs.com/default/pixy-cmucam5/ it can talk to arduino, and you can train it by telling it identify colored objects which i might think is apt for your case.
RFID tags will be a good idea as @Majenko said.

I'm making a "game" where the robot "fights" enemies that you direct him towards. Once the robot recognizes an enemy, he "fights" it (knocks it over) and the player gets a point (or something to this effect). The Pixy looks awesome, but I think it might be a bit too powerful for a project of this scope. Thank you for your response. I will do more research on RFID tags!

You can get an RFID reader for $7 from eBay:

Cards are around 30 cents:

I have example code for an entry control system which uses that reader.
The cards tend to activate at around 3 cm to 5 cm, so that sounds about right. Of course they aren't particularly directional, but if you are driving in a certain direction and it detects a card it is probably in front of you (however possibly off to one side).
You could combine card detection with simple range finding using an ultrasonic detector.

Oh, wow, this looks great! Thanks so much! I think this will be perfect.

Detecting colour with RGB illumination and an LDR is not particularly accurate in my experience.  The idea is you illuminate the card (or whatever) with red light, take an LDR reading, then with green then blue.
This gives you a set of 3 light levels for the different colour components of the object.  Combining them together gives you an RGB signature for the object.  Ideally, on say a red card, the value from the LDR under red illumination is much stronger, and blue & green much weaker.
RGB LED + LDR colour detection does work, but it's not accurate, and it helps to block out ambient lighting.  Maybe if you put a lot of time into calibration, it would for you.  I had a classroom of 14 kids, each made-up one of these circuits, yet only a couple had any moderate success, if at all.
That said, we were using very cheap RGB LEDs and similar quality LDRs.
There's a bunch of stuff you can do to help the accuracy, like subtract readings with only ambient illumination, take multiple readings, etc.
I think you would save yourself a lot of time and frustration buy using a purpose-made colour sensor.
Something like the ADAFruit Colour Sensor -  https://www.adafruit.com/products/1334

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


text:
while compare, something is wrong
I have 5 LDR and Arduino Mega. I connect them and get light level.
void loop() {
// print the analog output in milli volts
int w=analogRead(west);
Serial.print("west = ");

Serial.print(w);
Serial.println(" mv");

int e=analogRead(east);
Serial.print("east = ");

Serial.print(e);
Serial.println(" mv");

int n=analogRead(north);
Serial.print("north = ");

Serial.print(n);
Serial.println(" mv");

int s=analogRead(south);
Serial.print("south = ");

Serial.print(s);
Serial.println(" mv");

int c=analogRead(control);
Serial.print("control = ");

Serial.print(c);
Serial.println(" mv");

delay(1000);

if(e > w)
Serial.println("west");

else if(e < w)
Serial.println("east");

else if(s > n)
Serial.println("south");

else(s < n);
Serial.println("north");

Serial.println("\n");
}

This is my loop and I always see east-north. When west is bigger than east I also see east. What

What indeed @user3748265, what indeed.

It would help to post (under your code) what you see in the serial prints.

You should write out in plain English/language what you want to happen and then translate that to code. Your current program doesn't seem to follow any logic and it's hard for us to know your intentions. For example, your first if statement says if E is greater than W then print *west* - that's why you see "west" when E is bigger, but you are saying you don't want that.

Nick Gammon correctly points out a problem due to an extra semicolon, but you should also note what the construct else(s < n) is doing.  When the if condition that this else gives an alternative to is false, the statement   (s < n) gets executed.  That statement is an expression statement, and its value is the evaluation of s<n, either true or false.
If the semicolon after (s < n) weren't there, you'd get a compile error because (s < n) serial.println("north") is not a valid statement.  You may have meant to say else if(s < n) instead of else(s < n).
Note, in the sequence
if (e > w)
   Serial.println("west");
else if (e < w)
   Serial.println("east");
else if (s > n)
   ...

that last else typically is reached only rarely, because the only condition to get to it is e and w being equal.  Due to sensor noise and signal processing noise, the chance of e and w being equal is probably at most a few percent.
If your north/south test sequence is supposed to be independent of your east/west test sequence, leave out the second if and second else .  That is, instead say:
if (e > w)
   Serial.println("west");
else
   Serial.println("east");
if (s > n)
   ...

There is another issue I didn't want to comment on. E and W are read from different sensors, so you might conceivably have E == 1023 and W == 1023 which doesn't make a lot of sense. That's why I asked to see the actual serial output.

@NickGammon, I think user3748265 hasn't given enough info for us to say if equal values do or don't make sense.  In a suntracker, for instance, equal values are desired.   (If you're spotlighting maxed-out sensor values, I agree that's usually a problem.)

I won't contradict you. :)

Here:
else(s < n);
-----------^

That is wrong. See Arduino programming traps, tips and style guide.

Trap #13: Don't put a semicolon at the end of every line
Semicolons end statements. However if, for and while are compound statements, so they should not have a semicolon after them like this:
Wrong! ...
  if (temperature > 40);    // <----- this semicolon is incorrect!
    {
    digitalWrite (furnaceControl, LOW);
    digitalWrite (warningLight, HIGH);
    }

  for (int i = 0; i < 10; i++);   // <----- this semicolon is incorrect!
    digitalWrite (i, HIGH);

The semicolons above (as indicated) terminate the if and for so they don't do anything useful. The lines following them are just unconditional blocks of code which are always executed, once.
Correct:
  if (temperature > 40)
    {
    digitalWrite (furnaceControl, LOW);
    digitalWrite (warningLight, HIGH);
    }

  for (int i = 0; i < 10; i++)
    digitalWrite (i, HIGH);


text:
Physical dimensions(size) of the new MKR1000 board?
Anybody here knows the physical dimensions(size) of the new Aduino MKR1000 board?

If the diagram on the main page is to scale, then it's approximately 2.2 inches by 1.0 inches.

Exactly! I had the same figures in mind.


text:
Do I have a faulty arduino uno, or have I found an Arduino bug?
Lately, we got an old arduino uno donated from a friend and have been trying to get it to work with servos. We have been having very perplexing results. We have tried many different "stock" code and servo combinations with our servos, but here is the behavior:

180 Servos automatically move to right max as soon as power is applied.
Sail Winch servo moves a tiny amount and then stops. If power wire is removed and then reapplied, the servo moves another tiny amount.

The code is very simple. First we call the servo.attach(pin), and confirm the pin. We have also tried doing the manual uSec definition: servo.attach(pin, 600, 2400). In our loop() we have tried servo.write(*value from 0-180*) and servo.writeMicroseconds(*value in PWM range*)
Power is being supplied by a 9v battery, the sensor (yellow) is directly in digital pwm pin, while red (power) is in + and black (ground) is in -.
I'm trying to decide whether I should invest in another arduino system.
servos:
180 servos
Sail Winch servo

I'd invest in a better power source first.

@IgnacioVazquez-Abrams The 9v is for testing purposes, we have a better battery for the actual power source. Also why would investing in a power source take priority over a proposed faulty system?

Because a 9V battery is a terrible power source, especially if you have high-load devices such as servos.

@IgnacioVazquez-Abrams in what way is is terrible? Amperage? Would that affect how the servos respond to code?

When the servos try to move, they draw current. When the current increases, the voltage drops. When the voltage drops, the Arduino fails.

If the Arduino "fails" the moment you apply power to a motor, you can bet that it is a power issue.
Or possibly you are exceeding the output rating of the output pin. You should not draw more than 20 mA from each output pin continuously.

I'm trying to decide whether I should invest in another arduino system.

Power the motor independently of the Arduino. This is normal advice for all but very small motors. Also make sure that you have a suitable driving transistor / MOSFET if the motor draws more than 20 mA. Take into account any surge startup current.

See Driving motors, lights, etc. from an Arduino output pin for some design ideas.
For example:

We built a small battery out of several AA batteries lined in series connected to a bread board. That was our original power source. We were also using a separate 9v battery for ease of testing. The 180 servos are rated "Current Drain (6.0V): 7.7mA/idle and 180mA no load operating",  and the 360s rated "Working  Current: 0.30~0.35A ". Does this mean we need to have a "driving transistor"?

Your working current of 300 mA far exceeds the 20 mA continuous output of the processor (by over 10 times!). See amended reply.


text:
Splitting String from Serial
I am currently working on a program for an Arduino uno and want to, in the program, when it receives a 16 digit number from a serial transmition, it will split the 16 digit number into 4 separate 4 digit numbers.
For Example:
The computer sends the Arduino the number 1100115011001150 and I want the Arduino to break the number so that "Avalue" would equal 1100, "Bvalue" would equal 1150, "Cvalue" would equal 1100 and so on...
Thanks for any help you can provide!

Have you tried indexing the array in loops?

How does that work and what does that do?

@Buncey are you not familiar with for and while loops?

What is your actual question?

char ArrayBuffer[][4] = {};         // holds four characters, must be

declared as global to loop()
in
loop()
{
byte Index = 0;                    // initialize array index
if(Serial.available())             // have data in Serial buffer
{
byte Count = Serial.readBytes(ArrayBuffer[Index],4); // read       //4             //characters     into array buffer , returns actual number //of        characters //read and times out if less than 4 characters are //currently in Serial buffer
 Serial.println(ArrayBuffer[Index]); // print buffer to monitor
}while(++Index != 4);              // read 4 by 4 characters from incoming stream
}

...
continue with loop - process ArrayBuffer as required
}
This is one way to get the incoming stream from Serial buffer into for individual buffers, however, it is better, less chance of misdirecting the data into wrong buffer (index)  to read the entire buffer at once instead of using he readBytes four times.
Just my opinion, your mileage will vary.
PS what is the trick to format the code and text correctly ?
This is a mess.
I cannot get the code block to indent, I can get only the first ( four spaces line.

while (Serial.available() < 16);   // wait for 16 chars to come          easiest way to do this
for (int i = 0; i < 4; i++){      // for each number
    for (int j = 0; j < 4; j++){    // for each digit in the number
        nums[i] *= 10;
        nums[i] += Serial.read() - '0';

Where did my last post - comment on this code went?
It was suppose to wait for "peers" approval, per note I got after I posted it.
This is not the best way to use "available()", beside what will happen if 16 characters never arrive?

I do see your other answer, you probably had to wait a little.
You can now edit your old answer and delete this one.

int nums[] = {0, 0, 0, 0};   // must be always reset to zero if you will repeat this process
while (Serial.available() < 16);   // wait for 16 chars to come in; easiest way to do this
for (int i = 0; i < 4; i++){      // for each number
    for (int j = 0; j < 4; j++){    // for each digit in the number
        nums[i] *= 10;
        nums[i] += Serial.read() - '0';

//while (Serial.available() == 0);
//Serial.read();  // in case you use an extra character to separate numbers

A = nums[0];
B = nums[1];
C = nums[2];
D = nums[3];

If you are using a character or characters to delimit the 16-digit numbers being received, make sure to read off those extra characters before running the while loop again.

Not tested but should work.
int nums[] = {0, 0, 0, 0};
String inString = "";
while (Serial.available() >= 16) {
  for (int k =0;k<4;k++) {
    for (int i =0;i<4;i++) {
      int inChar = Serial.read();
      if (isDigit(inChar)) {
        inString += (char)inChar;
      }
    }
    nums[k]=inString.toInt();
    inString = "";
  }
  Serial.println(nums[0]);
  Serial.println(nums[1]);
  Serial.println(nums[2]);
  Serial.println(nums[3]);
}


text:
Defining object
I am trying to hide libraries behind another, for simplicity. But I can't deal with the objects required by the libraries. Basically I want to use the objects both in my .cpp and .ino file, but I am getting errors about double definition, or not declared in this scope.
test.ino
#include "lib.h"
#include "obj.cpp"

void setup() {
  mesh.setNodeID(40);
  mesh.begin();
}

void loop() {
  mesh.update();
}

lib.cpp
#include "Arduino.h"
#include "lib.h"

#include "obj.cpp"

int message = 1;

void send() {

  if (!mesh.write(&message, 'C', sizeof(message))) {

    // If a write fails, check connectivity to the mesh network
    if ( ! mesh.checkConnection() ) {
      //refresh the network address
      Serial.println("Renewing Address");
      mesh.renewAddress();
    } else {
      Serial.println("Sending failed, Test OK");
    }
  } else {
    Serial.print("Sent OK");
  }
}

lib.h
#ifndef lib_h
#define lib_h

void send();

#endif

obj.cpp
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
#include <EEPROM.h>

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

#include "obj.cpp"

Don't include .cpp files. That gets them compiled twice (or more) and then you get duplicate definitions. Include .h files only.
What you are calling obj.cpp should probably be obj.h, however I haven't actually tried to compile it.

it says that I have multiple definitions of the three objects

I tried compiling but I don't have the RF24 library. Anyway, this is wrong:
obj.h
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
#include <EEPROM.h>

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

You can't define things there (like radio) which get included in multiple files. obj.h or obj.cpp it will be the same thing.
These lines need to be in one .cpp file:
RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);

Thus you cannot include that file in another file. However you can refer to them by making them extern in a header file, eg.
extern RF24 radio;
extern RF24Network network;
extern RF24Mesh mesh;

I changed obj.cpp to obj.h but it says that I have multiple definitions of the three objects: sketch\test.ino.cpp.o:(.bss.mesh+0x0): multiple definition of mesh' sketch\lib.cpp.o:(.bss.mesh+0x0): first defined here sketch\test.ino.cpp.o: In function setup':
D:\test/test.ino:4: multiple definition of radio' sketch\lib.cpp.o:(.bss.radio+0x0): first defined here sketch\test.ino.cpp.o: In function setup':
D:\test/test.ino:4: multiple definition of `network'
sketch\lib.cpp.o:(.bss.network+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1


text:
Arduino Bluetooth data (large data files) transfer efficiency using HC05 module
Im using an HC-05 Bluetooth module connected to my Arduino MEGA. The Arduino has an SD card with some data files stored (sensor readings). After the sensor readings are done, the Arduino then connects to Android phone via Bluetooth and transfers the file data.
This is working fine. Arduino sends the data to HC-05 over Serial port, which transfers it over the air to my Android phone.
But its kinda slow and I hence had a question.
QUESTION: Does the HC-05 buffer the data coming from the Arduino Serial and then send efficiently filled packets over the air. I would like to make sure that the HC-05 isn't inefficiently sending just a single byte or so per Bluetooth packet.
Thank you.

Please add some performance measurement. What is "kinda slow"? Also add snippet of your sketch showing the serial baudrate and interaction.

Please upload your code, I will look into it.

What baud rate is the HC05 using? This will be the limiting factor. It can be changed up to 460800 baud (according to a random datasheet I googled).


text:
Unpacking Arduino binary data on a python sketch
As a follow up to my earlier post: Simultaneously reading data from multiple serial ports, I am stuck trying to develop a python sketch that can read the incoming serial data from the com port on my Arduino and unpack them from the buffer into two separate cvs files.
One of the csv files would contain the data from the first sensor, while the other would contain the data from the second sensor. I have been able to develop the sketch to a point where on receiving the first header byte the first sensor data is unpacked. I am finding it hard to adjust the sketch to allow for the second byte header to be called to unpack the second sensor data from the data packet. Below is my abbreviated sketch thus far. Thanks all.

def run(self):
    #Creating a csv file to read data from the first sensor
    self.click = open("ball_Data.csv", "wb")
    #Creating a csv file to read data from the second sensor
    self.flick = open("rugby_Data.csv", "wb")
    #creating the serial port object
    self.push = serial.Serial('COM6', 9600)
    while True:
        #If the incoming byte is equivalent to '$'
        if node == b'$':
            # the byte object is equivalent to the available bytes
            node = self.push.read()
            #an array to hold the sensor data
            sensor_array = []
            i = 0
            #This while loop initiates a count from 0 to 9
            #through the sensor array
            while i < 10:
                #The available byte present
                malcolm = self.push.read()
                #The next byte
                turnbull = self.push.read()
                #The incoming uint_16 data is unpacked into the variable lingo
                lingo= (struct.unpack('b', turnbull)[0] << 8) | struct.unpack('B',malcolm)[0]
                #The variable lingo is then appended to the sensor array
                sensor_array.append(lingo)
                #If the length of the sensor array is equivalent to 9
                #write the data through each count into the sensor array
                if len(sensor_array) == 9:
                    self.click.write(str(sensor_array[0] ..+ str(sensor_array[9]))
                    #My idea is that this else statement was supposed to trigger
                    #the next header for the second sensor which would be an '#'
                    #sign before unpacking the data
                    else:
                        oldde = self.push.read()
                        sensor_array = []
                        i = 10
                        while i < 20:
                            #The available byte present
                            malcolm = self.push.read()
                            #The next byte
                            turnbull = self.push.read()
                            lingo= (struct.unpack('b', turnbull)[10]<<8)|struct.unpack('B',malcolm)[10]
                            sensor_array.append(lingo)
                            if len(sensor_array) > 19:
                                self.flick.write(str(sensor_array[10]..+ str(sensor_array[19]))

                                The Packet data structure for the first and second sensor is:
                                    Packet1 from sensor 1:
                                        data_array[0] = headerbyte('#')
                                        data_array[1] = acceleration_xAxis
                                        data_array[2] = acceleration_yAxis
                                        data_array[3] = acceleration_zAxis
                                        data_array[4] = temperature
                                        data_array[5] = gyro_xAxis
                                        data_array[6] = gyro_yAxis
                                        data_array[7] = gyroz_xAxis
                                        data_array[8] = checksum
                                        Packet2 from sensor 2:
                                            data_array[9] = headerbyte('$')
                                            .
                                            .
                                            .
                                            data_array[17] = checksum

Please fix the code format. The indentation is "off".

@dada He means that it's a snippet and as such there is massive amounts of white space to the left of your listing that causes much of it to be scrolled off the side. You don't need to keep that indenting since it is not in context (which is actually an altogether different issue - we don't deal in snippets here : http://snippets-r-us.com ) so delete that excess indenting to make it easier to read, or better still, post your entire code so we might have a chance of understanding it.

@MikaelPatel, I adjusted the code format as requested.

and @majenko , I would comment more on the code to give you a better understanding of what i'm trying to do.

Can you post an example of the data that is being sent from the Arduino to your computer so that we know what it is that's trying to be parsed?

@majenko i just uploaded a screenshot of the data packet on the serial monitor

Urk. That's pretty meaningless like that I'm afraid. Can you create a packet description, similar to how I describe the ICSC packet format on here: https://github.com/MajenkoLibraries/ICSC

@majenko does this help

That's more usable, yes. Those are all BYTE values are they?

@majenko ..Yes they are

I'm somewhat confused by the flow of your program, so instead I will tell you how I would handle the data.
You have a single-byte header, then 7 bytes of data, followed by a single byte checksum.
PySerial's read is (I believe) blocking by default, so it's simple to read the next serial character - unlike an Arduino.  It also has a "multi-byte" read version where it can read a pre-set number of bytes from the stream for you.
So my methodology would be:

Read a byte.  Is it a '#' or a '$'?
If it is, remember which stream you are dealing with, then:
Read 7 bytes with this.push.read(7) into a byte array (or a string in python < 2.6)
Read one byte for the checksum. If the checksum is correct (whatever calculation you use for that) then unpack the data in the array.
Write the data to the correct file depending on the stream you remembered in step 2.

That way you're not duplicating code for each sensor stream, you are just saying "this packet is stream 2" and using that remembered fact once you have received the packet and verified that it's correct.
A better protocol arrangement, though, which is more reliable, involves both a start byte and an end byte, and your whole packet is wrapped in that pair of bytes.  You then have a "sliding window" arrangement whereby the incoming data bytes scroll past a window of a fixed width, and when the first and last characters in that window match your start and end bytes you then extract the middle section and do what you need to do with it.  That way if you have a $ or a # that is midway through a stream of data it won't trigger reception since the end byte doesn't match. It makes the whole synchronisation of the data more reliable.
For instance, if you have the current data packet that looks like $ho9*$fup and you miss the first bit of the data for whatever reason (arduino started transmitting before you were ready to receive, for instance) it might trigger reception on the second $ which would give you incorrect values.  So instead if you have the start character as $ and the end character as # and include a stream number, so your packet looks like:
$1ho9*$fup#

Then when you scroll that past the window it would look like:
 $         #
 v         v
[..........$]
[.........$1]
[........$1h]
[.......$1ho]
[......$1ho9]
[.....$1ho9*]
[....$1ho9*$]
[...$1ho9*$f]
[..$1ho9*$fu]
[.$1ho9*$fup]
[$1ho9*$fup#]

And the first and last characters match, so you receive the content.
If you were to miss the first $ the second $ wouldn't match - say the extended stream looks like: $1ho9*$fup#$2hdiw83bf# and you missed $1, the window would look like:
 $         #
 v         v
[..........o]
[.........o9]
[........o9*]
[.......o9*$]
[......o9*$f]
[.....o9*$fu]
[....o9*$fup]
[...o9*$fup#]
[..o9*$fup#$]
[.o9*$fup#$2]
[o9*$fup#$2h]
[9*$fup#$2hd]
[*$fup#$2hdi]
[$fup#$2hdiw] <= Doesn't match even though it starts with $
[fup#$2hdiw8]
[up#$2hdiw83]
[p#$2hdiw83b]
[#$2hdiw83bf]
[$2hdiw83bf#] <= Matches - starts with $ and ends with #

As you can see the synchronising of your packet is then much more reliable. It would normally have incorrectly triggered on the first $ it saw.
There is always a chance that there may be a $ and a # in just the right positions within successive packets to fool the system, but the chances of that are somewhat slim.  You can add extra protection against that by "escaping" the start and stop bytes if they appear within your stream. There's many possible ways of handling that if you really need it.

...Lord God!!! Thanks alot.!!!!!!!!!!!!!!!!!! ...I'm much obliged

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


text:
Is it possible to run the Teensy to the Arduino?
I'm already done copying/pasting the libraries that I know is needed to run the program, but I wonder why I always get this error every time I tried to run the code. What do you think would be the possible reason why I get this error:
  C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:64:14: warning:
  #warning Using current Arduino IDE with Wire library is functionally
  limiting.   [-Wcpp]

  #warning Using current Arduino IDE with Wire library is functionally limiting.

          ^

  C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:65:14: warning:
  #warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation
  is recommended. [-Wcpp]

  #warning Arduino IDE v1.0.1+ with I2CDEV_BUILTIN_FASTWIRE implementation
  is recommended.

          ^

 C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:66:14: warning:
 #warning This I2Cdev implementation does not support: [-Wcpp]

 #warning This I2Cdev implementation does not support:

          ^

 C:\Program Files (x86)\Arduino\libraries\I2Cdev\I2Cdev.cpp:67:14: warning:
 #warning - Timeout detection (some Wire requests block forever) [-Wcpp]

 #warning - Timeout detection (some Wire requests block forever)

          ^

 In file included from C:\Program Files
 (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:27:0:

 C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
 function 'bool RTIMUHal::HALRead(unsigned char, unsigned char, unsigned
 char, unsigned char*, const char*)':

 C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37: error:
'class HardwareSerial' has no member named 'printf'

 #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                 ^

C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:73:13: note:
in expansion of macro 'HAL_ERROR1'

         HAL_ERROR1("I2C read failed - %s\n", errorMsg);

         ^

  C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
  function 'bool RTIMUHal::HALWrite(unsigned char, unsigned char, unsigned
  char, const unsigned char*, const char*)':

  C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37: error:
  'class HardwareSerial' has no member named 'printf'

  #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                 ^

  C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:96:13:
  note: in expansion of macro 'HAL_ERROR1'

         HAL_ERROR1("I2C write failed - %s\n", errorMsg);

         ^

   C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp: In member
   function 'bool RTIMUHal::HALWrite(unsigned char, unsigned char, unsigned
   char, const char*)':

   C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.h:59:37:
   error: 'class HardwareSerial' has no member named 'printf'

   #define HAL_ERROR1(m, x)     Serial.printf(m, x);

                                 ^

  C:\Program Files (x86)\Arduino\libraries\RTIMULib\RTIMUHal.cpp:119:13:
  note: in expansion of macro 'HAL_ERROR1'

         HAL_ERROR1("I2C write failed - %s\n", errorMsg);

         ^

  exit status 1
  Error compiling.

Please add some information about the Arduino/Teensy IDE version, board, libraries used, etc. The compiler (and the source code) is trying to tell you that you have a severe configuration issue.

Many of your problems seem to be that you are trying to use Linux software on an Arduino. That's never going to work.

It just seems he's missing the right print function. It's worth a shot just  replacing the "printf" with "print". @Thomas, have you tried it (go to libraries folder, RTIMULib and open RTIMUHal in notepad and change line 59 "printf" to "print", keep everything else the same)?

Replacing "printf" with "print" will only lead to the "dark side" - even more compiler warnings. It might be the wrong version of the RTIMULib library.

Hi guys thank you so much for your responds :)

@Mikael Patel https://github.com/richards-tech/RTIMULib2-Teensy here is the link .

@Majenko, so you mean there's no chance to work it ?

@Avamander, i'll try it .

@MikaelPatel, yes i  used the teensy library because this is the latest,  a need to add the runtime calibration which is not present in this library. https://github.com/richards-tech/RTIMULib-Arduino


text:
How many bits can an Arduino uno read?
What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A single digital pin can only ever be either on or off.

Sounds like an X-Y problem - what are you really trying to solve?

Ah, GrassHopper.... when you can answer my question, you will know the answer to your own...    How big is a bit?

What is the maximum of bits that an Arduino can read on the digital input, which model in the Arduino range can read the most bits?

A digital input is by nature binary (i.e. a single bit). The answer to your question is therefore one bit per digital input.
The total number of digital inputs depends on the board. It ranges from Arduino Micro (which has fewest less with than 10) to Arduino Mega which has the most with more than 60).
Another possible interpretation of your question is the resolution of an analog pin (ADC). The AVR has max 10 bit resolution.
Cheers!

Do you mean simultaneous read or write? The AVR processors are 8-bit processors and their I/Os are grouped into 8-bit registers. If you configure all of the bits in a register to the same direction - all inputs or all outputs - then the entire 8 bits could be read/written at once. in C/C++ you would use the `PORTWhich I/Os are assigned to which register is designed into the chip - but the data sheet describes which physical pins are connected to which I/O register. You can take advantage of that to make use of a single register's-worth of pins for up to 8 signals that need to be set or read simultaneously.


text:
PID not working correctly
I'm currently working on a project where I need to use PID to get the correct speed for a motor when it is angled a certain amount.
The problem is that I'm only getting 0.00 and 255.00 as the speed. Nothing in between. The code is supposed to activate when the angle value is more than 1300 and less than -1300. The ax variable is from an MPU6050 sensor.
int16_t ax, ay, az;

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

void setup() {
  Input = analogRead(ax);
  Setpoint = 100;
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop() {
  accelgyro.getAcceleration(&ax, &ay, &az);
  int a=ax+10900;
  //Here I set the used variable to around 0. ax is actually around -10900
  //This is always true, this won't be in the final code. This is just making it work.
  if(1) {
    int val;
    val = map(a, -1300, 1300, 0, 1023);
    Input = val;
    myPID.Compute();
    Serial.println(Output);
  }
}

I suggest adding the symptom to the title as in the rejected edit http://arduino.stackexchange.com/review/suggested-edits/13084  The PID is working as configured, however these configuration parameters of the PID makes it oversensitive to the inputs, resulting in bang-bang operation and overshoot.   This failure mode is distinct from other PID failure modes in the 'Related' PID questions, and with a better title could help a user find or exclude this question and answer from their search.

If the values of 'a' and 'val' aren't used/useful for other purposes, you can control 'ax' directly.  If you want 'ax' controlled to the -10900 value, you can use ax as input and Setpoint as -10900 and avoid the offset, and mapping.  E.g.  PID myPID(&ax, &Setpoint,kP, Ki, Kd, DIRECT);  Setpoint=-10900;

How fast is your system compared to the loop() sampling time?  Does (100-map((ax+10900),-1300,1300,0,1024)) change appreciably during the sub-millisecond loop()?
With kI=5, an error of only 10 will saturate your 0-255 speed output in 26 iterations of loop(), potentially producing the behavior you see.  If you don't have control of your sampling time, the integral error can wind up (or down) to the process limits very quickly.
From https://www.arduino.cc/en/Reference/Map map() only linearly transforms the input data to the output data, but does not constrain() it to those limits.  If ax=-9000, then val would be greater than 1024.   Still, taking the normal working range of ax+10900 to be (-1300,1300) which is then mapped into  (0,1024), the Kp=2 term with a setpoint of 100 would produce a range of (-200,2048) constrained to the default (0,255) limits.
Working backwards from the setpoint of 100, through the 0-1024 map is 0.0975 along the (-1300 to 1300) range, or val = -949, or ax = -11849.  And the kP=2 times the mapping factor of 1024/2600 would change the output by 2*1024/2600=0.79 points for each step difference of ax from -11849.
The http://playground.arduino.cc/Main/MPU-6050 pages says the acceleration registers are 16 bit with high sensitivity, and suggests that 50 points of noise is a small variation.  If the sensor set for 16 bits for +/-2G into ax, then, each step change 60 micro-G.  If that is the source of your ax, then the small variations could easily saturate your control system, making it bang-bang between its output limits with only milli-G variations at the sensor.
Slow down your sampling time, reduce kI, and think of your Kp, Ki, and Kd as conversions of your measured and translated variable ax errors into output space (0-255 speed).
Also, in choosing a sampling time, consider how often you want the PID to make adjustments to the process.

Please respect others by presenting code that is readable. By doing that you may also find obvious errors in your code. Let me clean up the loop() and you will see what I mean.
void loop() {
    int a = ax + 10900;
    if (1) {
      int val;
      val = map(ax, -1300, 1300, 0, 1023);
      Input = val;
      myPID.Compute();
      Serial.println(Output);
    }
  }
}

So what is "int a = ax + 10900"? "ax" is not defined but the other use of it is as an analog pin number "Input = analogRead(ax)". And "a" is not used.
There is a condition that is always true "if (1)" and so on.
Cheers!

That was my fault when putting in the code but i fixed it.

It was supposed to be like it now. ( doesnt work)

Looks like you have much more to fix. How about the format? And the "ax" variable.

The format??? The ax variable is taken from an MPU6050 sensor.

Try to use indentation so that you code is more readable. This will also help you understand where you are going wrong. Here is a good reference on typical C++ style rules. https://google.github.io/styleguide/cppguide.html. Please post more of your code. Right now "ax" is not taken from MPU6050 sensor. That is not in your snippet. How could anybody guess that?

Ive added the code that you asked for.

And i do write out that i get ax from the mpu6050 sensor and that the value of ax is -10900. so the code is quite unnecessary.

So what do you think is the problem?

I believe that the PID is constantly overcompensating.

Because these are maybe too big? double Kp=2, Ki=5, Kd=1;

Where did these numbers come from? Estimation? Example code? Guesstimate?

What happens when output == 255 or output=0?

@Marc - so the code is quite unnecessary... that is quite incorrect... The code is necessary for us to fully understand what it is that is happening. Many times we have seen an OP emphatically stating that his code does "x, y and z" but then the code shows that it is actually doing "a, b and c", i.e., something quite different from what the OP expected and/or stated...


text:
Maintaining pull down on a relay with a shift register
I currently have an Arduino Mega project that uses a relay to switch some high voltage loads. Currently, I use a scheduler library so that every 250ms I check if certain conditions are met and if so I turn off or on the relay. The relay is active when pulled down.
I'm trying to figure out how to transition this project to using a shift register. If the pin needs to be pulled low to be turned on and I want to keep it on, how do I supply a steady "low" signal using a shift register if the register is clocked to only latch every 8 clock cycles (not to mention I only run this code every 250ms). Even if every bit that gets sent by the shift register is low, do I need to no longer use the scheduling library so that every time through the Arduino loop I am sending the low signal so that the low signal can remain constant? With the standard Arduino pin once I set it to low it stays low until I switch it to high. But with a shift register can I keep it low "until I switch it high?"

This is only a problem if you have an unlatched shift-register.

You have misunderstood how shift registers work - and one of the main reasons they exist in the first place.
Shift register ICs have a common 'latch' pin which latches the data present at the input of the cell into the cell, thus updating the output. Some ICs also offer an "output enable", which switches the outputs to a high-impedance state irrespective of the values in the cells - this might not be useful in your case, but the feature exists.
With a serial-to-parallel shift register you can shift in as many bits as you want, at whatever rate you choose, and the outputs will never change until you trigger a rising edge on the LATCH pin.

How a (latching) Shift Register works:
You have eight spaces within the register:
             ___    ___    ___    ___    ___    ___    ___    ___
[DATA_IN]-->|___|--|___|--|___|--|___|--|___|--|___|--|___|--|___|-->[DATA_OUT]
            BIT0                                              BIT7

The 'spaces' are chained together; at one end of the chain is the DATA_IN pin and at the other end is the DATA_OUT pin.
Every time there is a rising edge on the CLOCK pin, data is shifted down the chain from DATA_IN to DATA_OUT, one space at a time. For example, if the state of the 'spaces' is as the left hand column, then upon the rising edge of the CLOCK pin the spaces will change to the values in the right hand column:
 DATA_IN PIN = 1  ->  C  -> ?
BIT0 'SPACE' = 0  ->  L  -> 1
BIT1 'SPACE' = 1  ->  O  -> 0
BIT2 'SPACE' = 1  ->  C  -> 1
BIT3 'SPACE' = 0  ->  K  -> 1
BIT4 'SPACE' = 0  ->  E  -> 0
BIT5 'SPACE' = 1  ->  D  -> 0
BIT6 'SPACE' = 1  ->  G  -> 1
BIT7 'SPACE' = 0  ->  E  -> 1

You will see that BIT(n) changes to the value of BIT(n-1), with BIT0 changing to the value of DATA_IN. The DATA_OUT pin is used to daisy-chain multiple shift registers together. The important thing to note here is that the outputs do not change without a rising edge on the LATCH pin. You can pulse CLOCK as many times as you want, with whatever values on DATA_IN, and the outputs will not change. Ever.
When you finally trigger the LATCH pin, the value in each 'space' is latched into a second row of 'spaces' - these represent the outputs. On a latch trigger, the outputs therefore change to the values of the last eight bits that were shifted into the DATA_IN pin. For example:
OUTPUT = 11001010
                   SHIFT IN "01101111" (starting with RHS first)
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 01101111
                   SHIFT IN "11110000110011001100"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 11110000   i.e. the LAST EIGHT BITS that were shifted in
                   SHIFT IN "10"
                               TRIGGER RISING EDGE ON 'LATCH' PIN
OUTPUT = 10111100   again the LAST EIGHT BITS that were shifted in

It is generally never the case with a serial-in-parallel-out register that you would ever shift in less that eight bits at a time, so the last example is only there to illustrate the functioning of the IC.

Not all shift registers have latching.

Thank you for your response. Indeed, I do have a misunderstanding. There's one thing I'm still missing. If a relay requires a constant voltage, and the latch triggers every 8 clock cycles. How is a 'HIGH' signal maintained when using the shift register. Another way of putting it: if I have some code that runs on a scheduler every 1 second, and that code shifts all HIGH values into the register and latches it so it pushes a HIGH signal out, will the value drop to LOW between my 1 second intervals when I'm not actively pushing data.. if it does not shift to LOW, why is the HIGH value maintained?

@Inc1982 I've edited the answer, I hope this helps.

Thank you so much for the response. There's one small but important piece of information I'm missing. In my understanding a HIGH signal is say 40ma on an arduino pin, while a LOW signal is 0ma. In-between latches, is the signal kept constant until it is switched again? If so, that would imply that there is some constant power coming from the Arduino that is being fed through the shift register and out the pins. This must be separate from the 8 bits being pushing into the Arduino. Is that why shift registers need a separate power supply?

'High' and 'Low' signals have nothing to do with current; they refer to voltage. There is negligible current flowing between the Arduino and a shift register, at any time. The shift register provides the power to the devices it controls.

Ahh thank you that clarifies it for me. From: http://www.allaboutcircuits.com/textbook/digital/chpt-12/serial-in-parallel-out-shift-register/ "The purpose of the output register is to maintain a constant data output while new data is being shifted into the upper shift register section. This is necessary if the outputs drive relays, valves, motors, solenoids, horns, or buzzers." I didn't realize that after it latches it is able to keep in an output register the voltage differentials on each pin that you were describing.

That is watch 'latching' means.

... relay ... active when pulled down ... shift register ... latch ... Arduino ...

TPIC6C595
shiftOut() and the '595


text:
Arduino compiled sketch on sd card
Hello I have just got my Arduino to read text from a text file and it is running perfectly. I was interested in being able to load a sketch into the Arduino and having it execute it, from and SD card. The Arduino wouldn't be connected to my laptop at all. I researched it and it is possible, with a different boot loader. Which is a bit annoying because I don't want to change the boot loader on my Arduino. I could put it on a standalone atmega chip but lets pretend I don't have those. So I was thinking if you had pre-compiled Arduino code. Which is in hex format and ready to be put on the board, would it be able to be loaded from the SD card? If so how would I go about doing this?

Yes it is possible:
With a different bootloader.
You need something which will erase the old sketch from the chip, read the data from the SD card, and write that into the flash of the chip. The only thing that can do that is the bootloader or some external device (another ATMega328p chip which we have to pretend you don't have).
Due to the way the architecture works you can only execute code out of the flash, so you need to program your sketch into the flash somehow. And that is the role of the bootloader.

what if I had a sketch uploaded to the Arduino that uses about 50% of the flash space or more/less. If I had my really basic kind of language that I can load as a text file into a set of strings in the sketch's progmen. That part is possible. The sketch I write would be able to understand what the text file means.It might be just something like: print "hello world". That part is possible. Now the part I don't know about. When the sketch is finished with that "homemade language programme" it would have to clear it from its progmem and use those strings to load an new homemade language programme

If you were going to do that you could just read the text line by line from the SD card and act on it - no need to program anything into the flash.


text:
Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?
Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?
I would like to change the operation of a couple of Arduino pins from input to output during execution of the Arduino loop in an event-driven way. Is this possible please?

How do you mean "in an event driven way"? The Arduino has no events - maybe you are using some other software?

I mean that the functioning of certain pins as input or output would 'depend' upon some condition, some event happening one one of the other input pins.

The answer above is correct but the syntax is wrong (atleast to my knowledge).
The correct syntax is pinMode(pin, mode) copied from the original arduino.org post.Note:If I am wrong pls correct me

Yes.
Just call pinMode([pin], [mode]) whenever you want to change from input to output or output to input.
How to decide when to do that is entirely up to you. You can do it any time you choose using any stimulus you like.


text:
Arduino disecting a string
Hello I have a String that contains the following: "println('hello world')".
I want to be able to remove everything from the String except for the text insie the brackets. Bear in mind that this text will change multiple times as the programme runs. How can I remove everything except for what is in the brackets from the string.
    String line1 = "println('hello world')";

Please help me thx.

How can I remove everything except for what is in the brackets from the string?

There are a number of String class member functions that can help with this. First, indexOf(val) will help locate the character of interest. Second, substring() will help cut out the part you want. And as a bonus, using lastIndexOf() will allow brackets within the string.
String s = "println('hello world')";
s = s.substring(s.indexOf('(') + 1);
s = s.substring(0, s.lastIndexOf(')'));

Cheers!


text:
Trying to run two simultaneous loops that do the same task with different delay cycles
I'm trying to control a pellet stove auger motor in such a way that I can use a toggle switch to do High/Low (H/L) - so the way that I have it now is:
 void setup() {
   // initialize digital pin 13 as an output.
   pinMode(13, OUTPUT);
   pinMode(12, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(12, HIGH);
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2850);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(11250);

Which is just LED on/off but it also controls another relay that controls the blower motor - what I'm trying to set up is a H setting that would be the 2850 delay-ON - and then have say: pin 11 have a delay-OFF of 7000, and have pin 13 still resetting to the delay-ON of 2850.
What I mean is:

loop A: pin12 on -delay 2850 pin12 off -delay 11250
loop B: pin13 on -delay 2850 pin13 off -delay 7000

I saw and tried the code for 'multi-blink' - as the one I use is pretty much modified 'blink'.
Any assistance would be awesome - I run the one I show above now, on my pellet stove and it was recently -31.4 and worked like a charm, but I'd like to be able to have a high/low option.
PS: I also have a coffee roaster control project as well... help on that one is always appreciated as well.

Just out of interest... -31.4°C or -31.4°F? Although they are pretty much close, and damned cold either way!

The Arduino Simple Timer library (and other similar timer libraries) are made for exactly this kind of application. Your setup() routine calls the SimpleTimer library, naming a callback-function and how often it should get called. Your loop function must then call timer.run() reasonably frequently (where
reasonably frequently" depends on the timing accuracy and jitter tolerance of your application). timer.run() will call each of your callback-functions at its appropriate time. You write the callback-functions to do whatever you need them to do when the timer calls them.
There are one-shot timers and repeating timers - it sounds like your application could one of each per LED: One that fires periodically, to to call a turn-on-LED12 function every (ON_TIME_12+OFF_TIME_12) ms, and a one-shot that calls a turn-off-LED12 function, started by the turn-on-LED_12 function for (ON_TIME_12) msec. Same for LED13, ( ..., etc.)
Your loop function is free to do whatever else, as long as it calls timer.run() frequently enough that your application can meet its timing requirements.

This seems to be the perfect example for the simple scheduler:
#include <Scheduler.h>

const int pinA = 12;
const int pinB = 13;

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Scheduler.start(setupA, loopA);
  Scheduler.start(setupB, loopB);
}

void loop()
{
  Serial.print(millis());
  Serial.print(F(":pinA="));
  Serial.print(digitalRead(pinA));
  Serial.print(F(",pinB="));
  Serial.println(digitalRead(pinB));
  delay(1000);
}

void setupA()
{
  pinMode(pinA, OUTPUT);
}

void loopA()
{
  digitalWrite(pinA, HIGH);
  delay(2850);
  digitalWrite(pinA, LOW);
  delay(11250);
}

void setupB()
{
  pinMode(pinB, OUTPUT);
}

void loopB()
{
  digitalWrite(pinB, HIGH);
  delay(2850);
  digitalWrite(pinB, LOW);
  delay(7000);
}

Cheers!

Pretty amazing that only a couple of hours ago and now I have a written variant to try, which I tried something similar on the uno before, the code available at arduino for "multi-blink" but it wouldn't compile, but then i saw it said you needed a due, but not an uno to run it, but so didn't mess with it all that much, it made sense, but wouldn't run, and I failed to copy the error, but i'll def try running this, with pins of course, is there any reason it wouldn't run on a mega as well? The uno is busy keeping me warm, but I have a mega here, so I'll try that first

The Scheduler library above (lhttps://github.com/mikaelpatel/Arduino-Scheduler) can be used with more or less all Arduino boards. It gives the illusion of running multiple sketches in the same sketch.

I'm sorry man, i'm pretty sure i'm a dunce at this point - i tried all the ways i could find to include that and a different one as well, library, but still was unable to compile it = i don't get it, my understanding is that the code you posted would work with the library listed added - i'm certainly feeling shame in admitting I clearly don't know how to add a library to a sketch - help please.

Installing a library in Arduino is hard (at least the first time). Start by downloading the ZIP file from https://github.com/mikaelpatel/Arduino-Scheduler. Locate the "libraries" folder in the Sketchbook (or Arduino folder). Unzip the Arduino-Scheduler-master into the "libraries" folder and rename the folder Scheduler. Restart the Arduino IDE and you are ready to go.

It definitely doesn't help that the pc i'm using to code/try to code with is a 2012 hp $250 laptop that, as someone that has used computers since 1986+/- , is the WORST computer ever - tried upgrading to win10 from 7 - which was working fine, but i suppose i'm a bit of an early adopter , then, no touch pad at all, ditched the thing for a bit and just used phone, then needed to program the A unit to make the pellet stove work, so tried again, now, my touch pad does work, but, if you use the keyboard there is a oh, one to 1.5 sec delay before the touchpad works again - not stellar equpiment,

oddly, the first time i tried it was a zip, and i put it where it was supposed to go - i do try to follow directions most of the time (and do also mock those that don't), then i tried the rest of the options that were made available - i finally got it to say there was a , that was unexpected or some similar error, then pc was rebooted before getting the error copied - at this point... i don't get why it wont compile, it seems all the files are where they should be and the code makes sense, but...

WARNING: library Scheduler claims to run on [sam architecture(s) and may be incompatible with your current board which runs on samd] architecture(s).

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


text:
Pro Micro clone worked fine, now RxLED stays on and can't program it
I have burned out a few Pro Micro clones now. Initially I ran them using a 12VDC external raw power supply but two Pro Micro clones burned out pretty quickly this way. Another thread suggested that the Pro Micro clones use regulators that are not very robust. Since then, I've been using just USB power for my 5V/16MHz Pro Micro clones.
The third clone has been working fine on USB power only. I estimate that I uploaded a sketch I was working on about a dozen times. Suddenly the RxLED stayed lit and I can't upload to it anymore.
When I plug it in, Windows assigns a COM port successfully. The Arduino IDE sees the port and I can select it. This tells me the Pro Micro is not entirely dead. When I enable verbose mode for uploading in the Arduino IDE, here's what I get:
Sketch uses 3,914 bytes (13%) of program storage space. Maximum is 28,672 bytes.
Global variables use 148 bytes (5%) of dynamic memory, leaving 2,412 bytes for local variables. Maximum is 2,560 bytes.
Forcing reset using 1200bps open/close on port COM3
PORTS {COM3, } / {COM3, } => {}
[repeating 19 more times]
Uploading using selected port: COM3
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf -v -patmega32u4 -cavr109 -PCOM3 -b57600 -D -Uflash:w:C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Bartman\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.2/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .

and after some time:
avrdude: butterfly_recv(): programmer is not responding
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

On my working Pro Micro clone, I get the following after instead:
Found programmer: Id = "CATERIN"; type = S
    Software Version = 1.0; No Hardware Version given.
Programmer supports auto addr increment.
Programmer supports buffered memory access with buffersize=128 bytes.

Programmer supports the following devices:
    Device code: 0x44

avrdude: devcode selected: 0x44
avrdude: AVR device initialized and ready to accept instructions

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

avrdude: Device signature = 0x1e9587
avrdude: reading input file "C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex"
avrdude: writing flash (3914 bytes):

Writing | ################################################## | 100% 0.30s

avrdude: 3914 bytes of flash written
avrdude: verifying flash memory against C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
avrdude: load data flash data from input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex:
avrdude: input file C:\Users\Bartman\AppData\Local\Temp\buildb15cf522f4023b15f86cbd1c900761d6.tmp/sketch_feb15a.ino.hex contains 3914 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.04s

avrdude: verifying ...
avrdude: 3914 bytes of flash verified

avrdude done.  Thank you.

On the now non-functional one, I tried using a jumper from RST to GND, tapping this twice quickly in succession and uploading from the IDE in an attempt to recover the Pro Micro but this doesn't work.
I don't think it's a bootloader problem since the Pro Micro does get a COM port assigned to it but never-the-less, I tried burning a new bootloader from my working Pro Micro. Here's my Pro Micro to Pro Micro wiring:

In the IDE, I've selected:

Board: SparkFun Pro Micro
  Processor: ATmega32U4 (5V, 16 MHz)
  Port: [current COM port of working Pro Micro]
  Programmer: Arduino as ISP

But when I select Tools->Burn Bootloader, I get the following error:
Arduino: 1.6.7 (Windows 10), Board: "SparkFun Pro Micro, ATmega32U4 (5V, 16 MHz)"

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf -v -patmega32u4 -cstk500v1 -PCOM6 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xCB:m -Uhfuse:w:0xD8:m -Ulfuse:w:0xFF:m

avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Bart_S\AppData\Local\Arduino15\packages\SparkFun\hardware\avr\1.1.3/avrdude.conf"

         Using Port                    : COM6
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Is it permanently damaged? What are the next steps to troubleshoot this Pro Micro clone?

Try re-flashing the bootloader using another Arduino as ISP.

Is avr109/butterfly actually correct for use with a Pro Micro?  Avrdude man page says  "avr109/butterfly uses serial port to communicate with PC"  vs communicating via USB

SparkFun board support package is installed, Pro Micro board selected, 5V/16MHz processor selected. Works fine for my other Pro Micro

On that working setup, is the verbose output any different than above?

Of course it's different: there's a ton more output since it successfully programs. I'll add the working output to the question.

I've bricked my micros plenty of times. It turns out the bootloader mode only lasts about two seconds, instead of seven or eight "like they used to", so it's a bit of a trick to fix them. Squirrled away deep within the Sparkfun pages is this guide. If it works I'll solution-ify this.

I've seen this so called trick but I'm skeptical that the problem is with the bootloader since it boots up and generates a COM port in Windows.

results of trying to burn bootloader have been added to my question

Did you use a capacitor to avoid reset on the Arduino as ISP?

I didn't (I read this was required for the UNO as an ISP host) so I tried it with a 10uF tantalum between RST and GND on the ISP Pro Micro and get the same results.

Here is a solution https://petervanhoyweghen.wordpress.com/2012/09/16/arduinoisp-on-the-leonardo/. Cheers!

looked promising but the information there from 3 1/2 years ago of course no longer works with Arduino IDE 1.6.7 - I get no additional Programmer option in my IDE after adding the new hardware folder etc.

After many hours of unsuccessful bootloader reprogramming attempts, I was able to revive the Pro Micro by trying different timing of double tapping RST while the IDE was compiling/uploading a sketch. After several attempts the Pro Micro suddenly took a sketch and seems to be working now. Not sure how long it will stay this way or how often I will loose it and have to go through these shenanigans again.
Thanks to all for the help.

To make things simpler, try flashing the Pro Micro firmware with another UNO (or compatible) hardware. I prefer an UNO clone with CH340 chip or a pro mini with a FTDI cable. Just to keep things simple.
Flash the UNO with Arduiono as ISP sketch. Use connection guidance from Arduino tutorial:
Using an Arduino as an AVR ISP

Once this is done, AVRDUDE will see the source Arduino as AVR ISP and you can flash the firmware on the target Arduino.
You can also use this post for guidance as well.

I voted this up since I did successfully reprogram the bootloaders of all my Pro Micros using an UNO whereas I was unable to program them with another Pro Micro


text:
Arduino IDE programs Leonardo but cannot open serial terminal
I'm using Arduino: 1.6.7 (Mac OS X 10.11.3), Board: "Arduino Leonardo".
When I try to program my code, it works without problems.
When I want to open the built-in Serial Monitor or Serial Plotter, it says "Board at /dev/cu.usbmodem1421 is not available".
The board is available and my simple code even works using "SerialTools" from Mac App Store. So there must be some problem with the Arduino IDE.
No serial related messages on dmesg. Comically it mounts and umounts my Boot OS X and Recovery HD partitions every time I unplug the Leonardo.
hfs: mounted Recovery HD on device disk0s3
hfs: unmount initiated on Recovery HD on device disk0s3 hfs: mounted
Boot OS X on device disk2s3 ioqueue_depth = 64,   ioscale = 2 hfs:
unmount initiated on Boot OS X on device disk2s3

Any ideas?

int inByte = 0;         // incoming serial byte

void setup() {

    // start serial port at 9600 bps:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

}

void loop() {

  if (Serial.available() > 0) {
    inByte = Serial.read();
    Serial.println("Hi");
  }

}

did you ever solve your problem. If so, could you post the answer here please?

Could you be affected by https://github.com/arduino/arduino/issues/3495 ?


text:
What does it mean when there are two addresses listed in the data sheet for a particular register?
I have been trying to grasp a better understand of registers and port manipulation. I have been looking through the ATmega 328P datasheet to look at the different registers.
For some of the registers, I see that there are two addresses listed. For example, for PORTB is listed at 0x05 (0x25). Similarly, for its DDRB and PINB, they are listed at 0x04 (0x24), and 0x03 (0x23), respectively. What does this mean for the register? Thank you.

One (the lower number) is the IO port address which is used when using the IN or OUT op-code. The other (higher number) is the memory mapped address.
Different methods of access are more programatically efficient depending on how you are manipulating the values. For instance IN and OUT are more efficient at setting or reading the entire register value, but SBI and CBI on the memory mapped address are more efficient when manipulating individual bits.


text:
Arduino substring not working
Hello  I have an Arduino programme where a string is loaded from an SD card. That all works fine. I want to see if the string that has been loaded contains a certain phrase. I am using substring but it doesn't seem to be working. What am I doing wrong? Here's my code:
file = SD.open("/classes/basic.txt", FILE_READ);
 Serial.print("Reading, Checking and Compiling \n");
  while(file.available()) {
   character23 = file.read();
   content.concat(character23);
  }
if (content != "") {
  l1 = content;
  Serial.println(l1 + "\n");
}

if(l1.substring(0) == "print"){
  printlnMethod();
}
file.close();

it all works until it gets to l1.substring and that doesn't work because the method inside doesn't run. The string that gets loaded into the Arduino from the SD card is : println("hello world");
What am I doing wrong?

Substring takes either one or two arguments.
In the single-argument version that you are using the argument specifies the start of the substring. The substring then contines to the end of the string.  So, since you are asking it to start at index 0 the returned value is the entire string - from 0 to the end.
Instead you probably want to use the two-argument version. In that version you provide two numbers - the index in the string to start from, and the index in the string after the last character you want.  So if the string starts with "print" you then want to use l1.substring(0, 5) to get the characters 0 to 4 inclusive.

I already tried that and it didn't work

Try printing what substring returns so you can see what it's really doing. Your string might not be exactly what you think it is.

I'm not sure how to return a substring

Serial.println(l1.substring(0,5));


text:
MKR1000 not showing up on OSX
I can't appear to get my MKR1000 to list a port on my mac in the arduino ide, am i missing something obvious or does it need additional drivers?
Also
➜  ~  csrutil status
System Integrity Protection status: disabled.
running OSX 10.11.3
Board appears to be working, default led flashing

What does dmesg tell you?

i get a new lines 036284.257826 IOUSBHostDevice@14100000: IOUSBHostDevice::getDescriptorGated: type 0x03 index 2 length 2 completed with 0xe00002e8 and bytesTransferred 0 036284.258099 IOUSBHostDevice@14100000: IOUSBHostDevice::getDescriptorGated: type 0x03 index 1 length 2 completed with 0xe00002e8 and bytesTransferred 0

Is that what you get when you plug the mkr1000 in, or just while it's idle?

when i plug it in

Have you installed the drivers? (If there are any?)

Drivers not required apparently, though I am no expert, if I've missed some please let me know

Double click the reset button on the board. Then it will show in the Port list :-)

Worked for me, thanks! For others: don’t forget to install the board in Arduino board manager as described here: arduino.cc/en/Guide/MKR1000.

I also had to use another (shorter) USB cable.

See if this answers your question:
https://www.hackster.io/charifmahmoudi/arduino-mkr1000-getting-strarted-08bb4a
If not, go to your Board Manager (this happened to me too) and search MKR1000. There should be another install to do. Install that one and you should be good.


text:
Adafruit Trinket 3v with LED matrix backpack producing error
I have been wanting to create a Arduino watch. I built the circuit with an Adafruit Trinket 3v and an Adafruit LED matrix backpack (8*8). When I try to upload this example code:
/***************************************************
  This is a library for our I2C LED Backpacks

  Designed specifically to work with the Adafruit LED Matrix backpacks
  ----> http://www.adafruit.com/products/872
  ----> http://www.adafruit.com/products/871
  ----> http://www.adafruit.com/products/870

  These displays use I2C to communicate, 2 pins are required to
  interface. There are multiple selectable I2C addresses. For backpacks
  with 2 Address Select pins: 0x70, 0x71, 0x72 or 0x73. For backpacks
  with 3 Address Select pins: 0x70 thru 0x77

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

Adafruit_8x8matrix matrix = Adafruit_8x8matrix();

void setup() {
  // Serial.begin(9600);
  // Serial.println("8x8 LED Matrix Test");

  matrix.begin(0x70);  // pass in the address
}

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 };

void loop() {
  matrix.clear();
  matrix.drawBitmap(0, 0, smile_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();
  matrix.drawBitmap(0, 0, neutral_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();
  matrix.drawBitmap(0, 0, frown_bmp, 8, 8, LED_ON);
  matrix.writeDisplay();
  delay(500);

  matrix.clear();      // clear display
  matrix.drawPixel(0, 0, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawLine(0,0, 7,7, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawRect(0,0, 8,8, LED_ON);
  matrix.fillRect(2,2, 4,4, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.clear();
  matrix.drawCircle(3,3, 3, LED_ON);
  matrix.writeDisplay();  // write the changes we just made to the display
  delay(500);

  matrix.setTextSize(1);
  matrix.setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
  matrix.setTextColor(LED_ON);
  for (int8_t x=0; x>=-36; x--) {
    matrix.clear();
    matrix.setCursor(x,0);
    matrix.print("Hello");
    matrix.writeDisplay();
    delay(100);
  }
  matrix.setRotation(3);
  for (int8_t x=7; x>=-36; x--) {
    matrix.clear();
    matrix.setCursor(x,0);
    matrix.print("World");
    matrix.writeDisplay();
    delay(100);
  }
  matrix.setRotation(0);
}

I get this error:
Build options changed, rebuilding all
In file included from matrix8x8.ino:23:0:
C:\Users\My_Username\Documents\Arduino\libraries\Adafruit_LEDBackpack/Adafruit_LEDBackpack.h:30:24: fatal error: TinyWireM.h: No such file or directory
  #include <TinyWireM.h>
                        ^
compilation terminated.
Error compiling.

I have installed TinyWireM, Adafruit_GFX, and Adafruit_LEDBackpack. Why would I get this error?

Because the TinyWireM library isn't properly installed.

How would I properly install it? What could have gone wrong?

How did you install it? You must have done something wrong...

I got the .zip from github.com/adafruit/TinyWireM and then put the folder inside Documents\Arduino\libraries.

What is the name of "the folder"?

Remember to remove the "-master" from the library folder name.

The name of the folder is TinyWireM.


text:
Why doesn't my object's method return back to my caller method?
I am creating a miniature computer using an Arduino, and I am creating a full-scale interpreter for it. Everything works, and the code begins to run after calling the runCode method, but once the run is finished it doesn't return to the calling function. I have Serial outputs to tell me where the code reaches.
My code contains an "Function" object with a name and a function pointer, an object to run the code (with a working Lexer object that splits the inputted code by spaces), and an in-computer editor (which completely works except the one function) to input programs to be run.
The function that calls the runCode method for my code-running object (called Joker) is in the editor. The problem is, once the runCode finishes, it does not return. The system halts. I will post the Function class, runCode Method, and calling method.
P.S. There are Serial prints to determine where the code reaches. It outputs "Function End!", but not "Failed!"/"Succeeded".
P.P.S. It uses a parallax 4x20 Back-lit Single-pin Serial LCD which completely 100% works.
P.P.P.S It uses the QueueList library which is basically a dynamic list that works like a stack.
One more note: The code heavliy uses dynamic lists, function pointers, and lambda expressions, so.... be prepared....

Code for Function class (no it does not have any actual functions):
class Function {
public:
  String f_name;
  bool (*f_run) (QueueList<float> &stack, SoftwareSerial &lcd);
};

Code for runCode method:
bool Joker::runCode(QueueList<String> lineTable, SoftwareSerial &lcd) {
  // Set up lexer
  Lexer lexer;
  // Get all lexer words
  lexer.getWords(lineTable);

  String cur_word = "";
  float num_val = 0.0f;
  bool quit = false;

  while(!quit) {
    cur_word = lexer.nextWord();
    if(cur_word == "")
      quit = true;
    else {
      // Get word in uppercase
      cur_word.toUpperCase();

      Serial.println(cur_word);

      // Parse the first number from it
      num_val = cur_word.toFloat();

      // Check if we have a function
      if(queueListContains(cur_word, dictionary)) {
        Function theFunc = getDictionaryFunction(cur_word, dictionary);
        if(!theFunc.f_run(stack, lcd)) {
          error(F("Unable to process word!!"), lcd);
          return false;
        }
      } else if(num_val != 0) {         // check if the parse was good
        stack.push(num_val);            // if it was: push num to the stack
      } else if(num_val == 0) {         // if zero it could be parsing a zero or it could have failed
        if(cur_word.indexOf("0") != -1) // if it didn't fail:
          stack.push(num_val);          // push to the stack
        else {                          // otherwise:
          error(F("Unknown word!!"), lcd);   // Unknown word error
          return false;
        }
      } else {
        error(F("Unknown word!!"), lcd);
        return false;
      }
    }
  }

  // Test printing the stack
  /*while(!stack.isEmpty()) {
    lcd.print(stack.pop());
    lcd.print(' ');
  }*/

  Serial.print(F("Function end!"));
  return true;
}

And the caller method:
void line_editor::RunProgram(SoftwareSerial &lcd) {
  Serial.println("Running program!!");
  // Move to top line
  currentLine = 0;
  while(!lineTableB.isEmpty()) {
    lineTableA.push(lineTableB.pop());
    // Serial.print(lineTableB.peek());
  }

  // Clear the string
  lcd.write(12);
  delay(5);
  lcd.write(128);

  // Joker language object
  Joker joker;

  QueueList<Function> PrintingWords;

  // Create the printing functions
  Function printWord;
  printWord.f_name = "BC"; // print "Beginning Card"
  printWord.f_run = [] (QueueList<float> &stack, SoftwareSerial &lcd) {
    if(stack.isEmpty()) {
      return false;
    }

    float num = stack.pop();
    lcd.print(num);
    lcd.write(13);

    return true;
  };
  PrintingWords.push(printWord);

  // Print the whole stack
  Function printStack;
  printStack.f_name = "AC"; // print "All Cards"
  printStack.f_run = [] (QueueList<float> &stack, SoftwareSerial &lcd) {
    while(!stack.isEmpty()) {
      lcd.print(stack.pop());
      lcd.print(' ');
    }

    lcd.write(13);

    return true;
  };
  PrintingWords.push(printStack);

  // Add all the functions
  joker.addWords(PrintingWords);

  // Run Program here...
  if(joker.runCode(lineTableA, lcd))
    Serial.println("Success!!");
  else
    Serial.println("Failed!!");

  // lineTableA.push(lineTableB.pop());

  Serial.println("Here!!");

  return;
}

Sorry if I confused anyone. If there are any questions, then leave a comment, and I'll try to clear up the confusion. Any help would be appreciated.
EDIT::ADDING FULL CODE:
Here is a LINK to the rest of the code on github.
Also, here is the rest of the Joker.cpp:
void Joker::addWords(QueueList<Function> new_dict) {
  while(!new_dict.isEmpty()) {
    dictionary.push(new_dict.pop());
  }
}

bool Joker::queueListContains(String theWord, QueueList<Function> &list) {
  Serial.println("Finding word:");

  QueueList<Function> temp;

  while(!list.isEmpty()) {
    Function r = list.pop();
    temp.push(r);

    Serial.print(">> ");
    Serial.println(theWord);
    Serial.print(">> equals? ");
    Serial.println(r.f_name);
    delay(5);

    if(r.f_name.equals(theWord)) {
      while(!temp.isEmpty())
        list.push(temp.pop());
      return true;
    }
  }

  while(!temp.isEmpty())
    list.push(temp.pop());

  return false;
}

Function Joker::getDictionaryFunction(String theWord, QueueList<Function> &list) {
  QueueList<Function> temp;

  while(!list.isEmpty()) {
    Function theFunction = list.pop();
    temp.push(theFunction);

    if(theFunction.f_name.equals(theWord)) {
      while(!temp.isEmpty()) {
        list.push(temp.pop());
      }
      return theFunction;
    }
  }
}

void Joker::error(String message, SoftwareSerial &lcd) {
  lcd.write(12);
  delay(5);
  lcd.write(128);

  lcd.print(message);

  delay(2000);
}

And the header:
#pragma once

class Joker {
private:
  bool queueListContains(String theWord, QueueList<Function> &list);
  Function getDictionaryFunction(String theWord, QueueList<Function> &list);

public:
  QueueList<float> stack;
  QueueList<Function> dictionary;

  void error(String message, SoftwareSerial &lcd);
  void addWords(QueueList<Function> new_dict);
  bool runCode(QueueList<String> lineTable, SoftwareSerial &lcd);
};

Please post a Minimal, Complete, and Verifiable example.

What Arduino board and IDE version are you using? Most boards have very limited amount of memory.

He tagged it Mega.

In principle, I would avoid the String class, because that could fragment memory. However in this particular case, it is probably something more sinister.

The full code link was a very very very bad way to upload code.

@MikaelPatel Don't mind me asking, why was it a bad way?

The short answer here is - It does not return because you have corrupted the stack.
The return address is pushed onto the stack as part of the function call.  If you overwrite (corrupt) that address the program cannot jump back to where it was (return).
So where is the cause of the problem?
Does getDictionaryFunction(cur_word, dictionary) ever return NULL or an invalid pointer?  The code tries to execute it anyway.  EDIT: What happens below when theWord is not matched or list is empty?  Actually I'm surprised this compiles, since there's a few paths where no value is returned.  (I'm no expert on the GCC AVR compiler, but what happens if we don't assign a return value at all?)
Function Joker::getDictionaryFunction(String theWord, QueueList < Function > &list)
{
    QueueList < Function > temp;

    while (!list.isEmpty())
    {
        Function theFunction = list.pop();
        temp.push(theFunction);

        if (theFunction.f_name.equals(theWord))
        {
            while (!temp.isEmpty())
            {
                list.push(temp.pop());
            }
            return theFunction;
        }
    }
    // BAD-JUJU HAPPENS IF WE GET HERE
    assert(false);
}

Coding style tip: except in trivial cases, it's good to only return from the bottom of your function.  Then the above never happens, and supposedly it's easier for the compiler to optimise.  NOTE: I'm unsure if assert() will even do anything on Arduino.  It's left as a marker to mean Handle Error Here.
Function Joker::getDictionaryFunction(String theWord, QueueList < Function > &list)
{
    Function dict_func = NULL;
    QueueList < Function > temp;

    while (!list.isEmpty())
    {
        Function theFunction = list.pop();
        temp.push(theFunction);

        if (theFunction.f_name.equals(theWord))
        {
            while (!temp.isEmpty())
                list.push(temp.pop());
            dict_func = theFunction;
            break;
        }
    }
    assert(dict_func != NULL);  // This should never happen
    return dict_func;
}

Coding style tip: WoRd CasE ~ lower_case, mixedCase, CapitalCase, UPPER_CASE.  I use lower case for all_variable_names, mixed case for functionNames(), capital case for ClassNames and StructureNames, and upper case for MACROS and CONSTANT_DEFINITIONS.  Pick a system, and stick to it absolutely.
Have you run out of memory - the stack could have hit the heap.
What sort of Arduino are you using?
On an Uno, with only 2k of RAM, you might need to make some scope-cuts.
Even on an Arduino Mega, you still only have 8k.
Maybe you can make use of a freeMemory() function.  This will give you an indication of the free space between the stack and the heap.  The AdaFruit version is below, but there are others too.
int freeRam ()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

It may be worthwhile reading their page on Arduino memory usage.
So after having a browse through your code, I can't see any obvious problems.  Fix the getDictionaryFunction() so you know if it's failing.  Check to see if you're running out of RAM - you are making heavy use of it copying strings around, especially with that template class.
Maybe consider re-compiling the code on a workstation in GCC - it wouldn't take much, just change your serial outputs to printf(), and hard-code your input data (or read from a file).  That will enable easier debugging.

He has a Mega, from the tags. However I agree in principle that the stack is probably corrupted. Why, it is hard to say from that snippet.

@NickGammon I will add the rest of the code.

I was hoping for a minimal example that demonstrates the issue.

Agreed - dude is clobbering the stack. Not surprising, considering what he is trying to make his arduino do.


text:
do digital input pins act as a positive or negative
I've gotten contradicting information on the subject.  Some say that digital input pins send out positive voltage, and if it goes to ground (for example) it reads LOW but if the pin is connected to power, it will read HIGH.  On the other hand, some say that the input pin is receiving voltage from either power (+5V) or ground (0V).  which one is it?

Digital pins sink or source current. They don't provide negative voltages. If the pin is set to INPUT then it is high impedance and will not "send out positive voltage".
However if you activate the internal pull-ups, as Ignacio said, then effectively the pin is connected to +5V via (approximately) a 50k resistor.

It's both, depending on whether or not the internal pullup has been enabled (INPUT versus INPUT_PULLUP). The pullup ties the input to the positive supply through a moderately large resistance, meaning that it is possible to source a small amount of current from the input pin.


text:
Arduino to breadboard with LM35 temp sensor
I have moved the MCU of the Arduino to a breadboard using these steps https://www.arduino.cc/en/Main/Standalone then interfaced it with an LM35 temperature sensor to the ADC0. But I can't get proper values from the LM35. I think it's because of the Aref or AVcc. Both are just connected to +5?
Here is my code:
float tempC;
float reading;

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

void loop()
{
    reading = analogRead(0);
    tempC = (reading * 0.4882815) + 5;
    Serial.print(tempC);
    delay(1000);
}

I get hex values and sometime high values. What to do with Aref and AVcc?
EDIT: I get values like these
€
Œ

Hex values? Can you copy and paste some of them into your question please?

I get values like €
Œ

Well, that isn't hex, that's mumbo-jumbo. I suspect you are not operating at the correct clock rate. Do you have a crystal on your breadboard? If so what frequency is it? If not, how do you have the fuses configured?

Yes I have a crystal. It says 22.000C16 at the top. I thought I bought a 16MHz oscillator. Now I'm doubting. So you think it's the crystal oscillator's fault?

Well, if it worked on the Arduino board, but not on your breadboard. Make a simple test, like flashing an LED every ten seconds. Time how quickly it flashes on your breadboard.

Okay so I tried a simple flashing LED every second. And clearly it's not flashing every second. So the problem is the oscillator hmm? I'll buy a new one later and test it again to see if the problem persists. Thank you Nick

For what it is worth, with the clock rate wrong, you baud rate may also be wrong.

Also why the +5 in your calculation? Make tempC and reading ints as well

I haven't bought any 16 MHz crystal. What will I do? :(

You can configure the fuses to work from the 8 MHz internal oscillator, and then if you compile for 8 MHz Lilypad, that should give you the right baud rate.

Check the baud rate of your serial monitor matches what you have set in your setup() function.  In the above code that is 9600.  If the baud rate is incorrect you typically get rubbish output in the serial monitor.

You may also want to change the Serial.print(tempC) to
Serial.println(tempC,2);

To get some decimal places.
As for the circuit ~

You don't need ARef connected.
The LM35 VCC should be connected to Arduino 5V
The LM35 GND to Arduino Gnd (any of them)
Finally LM35 signal (Vout) to Arduino A0.

Thanks for answering but my baud rate is correct and adding ",2" did not help :(

Hanging ARef didn't change anything. The next three steps I did already. Nothing changed

@user5434720 - Your circuit looks like the diagram right?

No sir since I moved the MCU to a breadboard. I'm not using the Arduino board anymore

clearly it's not flashing every second.

Is it flashing about every .73 seconds? That would be the period you'd expect if you have a 22.000MHz crystal: period = (16/22 * 1.00 sec). (If so, that is a rather high over-clock rate for the chip but suggests just how hardy they really are.)

I haven't bought any 16 MHz crystal. What will I do?

Buy a 16MHz crystal. That's the right fix. But you might (if I guessed correctly that you have a 22MHz crystal) - might - get away with trying a baud rate of (16/22) times your present baud rate, de-rating it to compensate for the clock rate. Be as precise as you can. You'll need to reprogram the chip with your Arduino board because the chip's bootloader expects a 16MHz clock.
Or, if it's not 22MHz, you could time a number of blinks (50 or 100), calculate the clock rate error, and re-calculate a baud rate the way I did above. Use a lower baud rate to start with; it is likely to be less affected by small timing errors.