text:
Arduino digitalWrite 1 or 0 instead of HIGH or LOW
Is it ok to use
digitalWrite(pin, 1) instead of digitalWrite(pin, HIGH)

or
digitalWrite(pin, 0) instead of digitalWrite(pin, LOW)

I want it that way to make the coding lesser because I save values on EEPROM with 1's and 0's. So if I want to use EEPROM value, I can call it this way
digitalWrite(pin, EEPROM.read(1))

I have no arduino to test now, but my bet is it's possible. HIGH and LOW are just constants for 1 and 0.

As a continuation to all the answers, the result of HIGH and LOW being #defined is that there is no change in compiled binary size -- only more descriptive names in source files (which is why they are recommended). The preprocessor converts HIGH into 0x1 and LOW into 0x0 for you.

Yes, that is fine.  LOW is 0 and HIGH is 1.  digitalWrite() sets the output to off if it receives a 0 and on if it receives anything of 1 or more.
That means that these are all equivalent:
digitalWrite(pin, HIGH);
digitalWrite(pin, 1);
digitalWrite(pin, 69);

It's especially useful when you are examining a variable for, say, a certain bit being set:
digitalWrite(pin, bytevar & 0x80);

That will set the pin to high on any value from 128 to 255 in the byte variable, and low for anything below 128.

From the arduino source code:
#define HIGH 0x1
#define LOW  0x0

So HIGH is exactly the same as 1. And LOW exactly the same as 0.

Exactly, and since HIGH == 1, then you could save HIGH to the EEPROM.

Also HIGH - HIGH == LOW (-;

This misses the point. The question is: is LOW guaranteed to always be 0 and is HIGH guaranteed to always be 1? Looking at the current source code provides no answer to that question.

@AnT HIGH and LOW are Arduino specific. Arduino doesn't have a specification like for example C, C++, or Forth. So looking at the Arduino source code is currently the best way to determine this. Can they change their code tomorrow? yes. Is this likely? Not in the slightest.

it doesn't have a type? As in if I want to declare a variable state and assign it a value HIGH or LOW later on, should i declare state as an int or something else?

@rfii #define is a macro. So the preprocessor replaces all the occurrences of HIGH and LOW with 1 and 0, before the result goes to the compiler. So, to the compiler, it looks as if you would have written 1 and 0. Or did a find&replace yourself. So it doesn't have a type, but can be seen as a string.

When you look at the source code of Arduino, HIGH is defined as 1 and LOW is defined as 0 using #define.
You may heard about Preprocessor, Compiler, and Linker. When you build the project, preprocessor do its job before the code is compiled. What the preprocessor does is basically converting defined words into corresponding value.
For example when you write a syntax like:
digitalWrite(1, HIGH);

When you build your project, the preprocessor converts the above like into this:
digitalWrite(1, 1);

Then the code is compiled. Therefore, there is no difference between HIGH and 1.
So, if the result of EEPROM.read(1) is either 0 or 1, there should be no problem.


text:
#define macro not in scope when i try to use IR library
My code keeps saying that that Button_8 and the rest of the #define macros are out of scope.
#include <IRLib.h>
#include <Servo.h>

#define MY_PROTOCOL SONY
#define RIGHT_ARROW   0xfd50af //Move several clockwise
#define LEFT_ARROW    0xfd10ef //Move servo counterclockwise
#define SELECT_BUTTON 0xfd906f //Center the servo
#define UP_ARROW      0xfda05f //Increased number of degrees servo
#define DOWN_ARROW    0xfdb04f //Decrease number of degrees servo moves
#define BUTTON_0 0xfd30cf  //Pushing buttons 0-9 moves to fixed  positions
#define BUTTON_1 0xfd08f7  // each 20 degrees greater
#define BUTTON_2 0xfd8877
#define BUTTON_3 0xfd48b7
#define BUTTON_4 0xfd28d7
#define BUTTON_5 0xfda857
#define BUTTON_6 0xfd6897
#define BUTTON_7 0xfd18e7
#define BUTTON_8 0xfd9867
#define BUTTON_9 0xfd58a7

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;
long Previous;
Servo myservo2;
Servo myservo;

void setup()
{
myservo.attach(8);
myservo2.attach(3);
My_Receiver.enableIRIn();
}

void loop()
{

  if (My_Receiver.GetResults(&My_Decoder))
{
   My_Decoder.decode();
   if(My_Decoder.decode_type==MY_PROTOCOL)
   {
       if(My_Decoder.value==0xFFFFFFFF)
       My_Decoder.value= Previous;
       if(My_Decoder.value == Button_9)
       {
       myservo.write(0);
       myservo2.write(180);
       }
     else if(My_Decoder.value == Button_8)
      {
         myservo.write(180);
          myservo2.write(180);
       }

    }
}
}

when i use a switch statement instead of the 4 and 5 if statement like so:
switch(My_Decoder.value) {
        case Button_8:   //do something; break;

it works, but i dont know why.

C++ is case-sensitive. Button_8 is different from BUTTON_8.

source: Stack Exchange

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

sort: votes


text:
I'm looking for a real small but decent Arduino, that can fit in a watch but power a servo and a gyroscope
I've been scouring the internet looking for a small Arduino that can power two sensors and a servo. Is there a way of getting a custom one? Does anyone know if theres software out there for creating custom Arduinos and having them made?

You might look into building a circuit, on a breadboard, from basic components. Think Atmel, AtMega instead of Arduino. Depending on your experience and willingness to read datasheets, this might be easier than you imagine. After you have a large-scale working prototype, find miniature surface-mount versions of all of the components. Designing an actual circuit board to connect these things might be the real trick, but if you can get it done then you can have the board made. I believe, am uncertain about this, that there are software tools available that help turn schematics into circuit board designs. This part might be expensive. Getting to the point of having a large-scale working prototype, on the other hand, would be inexpensive and fun. Once you have a board designed you'll have to get it made. Testing this prototype might be difficult and perhaps expensive as well. (Engineers are paid well because they tend to know before construction if a design will work.) If you come up with something that works then selling the extras might pay for having it made.

No, there is no software specifically for designing custom Arduinos.  However, the Arduino is open source, so you can design your own if you have the skills.
You can download the schematics for your chosen base design from the Arduino website, then use any PCB design software you like to design your own PCB.
You can then send that PCB design off to China (for example) to have it fabricated, and when you get them back you can solder the components on and hope it works.
Of course, designing and building very small circuits well is a talent that few possess. Hand building circuits with the very tiny components you will need to make it fit into a watch is very difficult and normally requires specialist equipment.  That is unless you want your watch to be the size of a dinner plate, like most of the watch kits you can buy.

If you do not want to send the design to china and live in the US https://oshpark.com/  has some great rates and are hobbyist friendly.

Look at the ATtiny85 MCU. It's a small 8pin device, and pretty easy to get up and running using Arduino code. You could also use the ATtiny84 which has more pins and still very small.
Start here: https://code.google.com/p/arduino-tiny/
Also, there are plenty of tutorials on setting up and programming them.
Regarding a custom board, your least expensive route would be to design your own. Otherwise you would need to outsource the design.

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


text:
does ATtiny85 handles the size of the libraries mentioned below `<MD_Parola.h>` and `<MD_MAX72xx.h>`
The ATtiny85 microcontroller has very limited resources, including program memory (flash) and RAM. It has 8KB of flash memory and only 512 bytes of RAM.
does ATtiny85 handles the size of the libraries  mentioned below
<MD_Parola.h> and <MD_MAX72xx.h>
what microcontroller would you recommend?
https://www.arduinolibraries.info/libraries/md_max72-xx
https://reference.arduino.cc/reference/en/libraries/md_parola/

Can you at least please give a link to the libraries you mention? Are you expecting us to Google for where they are and then read all the documentation for them? Asking for recommendations is a bit broad. It depends. What else are you trying to do? What are your price constraints? A quick Google search indicates the libraries do not mention what processor they target, so it is hard to answer. Just as a guess (and this is a guess) they probably are for the larger processors like the Atmega328P.

Thank you @NickGammon for the quick response. Please  find the docs reference of the library and I will check Atmega328P
https://reference.arduino.cc/reference/en/libraries/md_parola/
https://www.arduinolibraries.info/libraries/md_max72-xx

It is very simple to test.

Install the ATTinyCore in IDE
Install the MD_Parola library in Library Manager. It will install the MD_MAX72xx library too
Go to IDE Examples menu, search for the MD_Parola library examples and select the Parola_HelloWorld example
select the ATTiny85 in the Tools menu
hit Verify

output:
avr/bin/ld: region `text' overflowed by 11820 bytes
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board ATtiny45/85 (Optiboot)

which means it will not fit.
If you select Arduino Uno in the Tools menu and Verify you get:
Sketch uses 20692 bytes (64%) of program storage space. Maximum is 32256 bytes.
Global variables use 288 bytes (14%) of dynamic memory, leaving 1760 bytes for local variables. Maximum is 2048 bytes.

thank you @Juraj !!!I will consider Atmega328P

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


text:
TMC2208 Stepper Motor does not change its RPM linearly
This is my first project working with stepper motors, so I may have a bit of a shaky understanding of the electronic side of the project. I'm trying to create a simple device with 4 buttons connected to a stepper motor driver/NEMA 17 motor, with the ability to increase/decrease RPM, switch motor spin direction, and run the motor with the button being held down. (LCD screen included for output as well)
I'm noticing that when changing the RPM on my motor, i.e. from 3.2 to 3.1 to 3.0, the speed of the motor is really slow, then when set to 3.0, suddenly increases a lot, but goes down when setting the RPM back down to 2.8 or so. This occurs multiple times along different intervals of RPMs that I have tested as well.
I think that there may be an issue with the method with which I am calculating the pulse delay given the RPM in my function setRPM() at the end of my code or with the way that I am micro-stepping, which I am doing because I need extremely precise movement.
Included below is the code that I used to run with my TMC2208 driver. (Sorry if it is rather long, but I included comments to document my thought process when programming the Arduino.)
Included list of RPMs and pulse delays

rpm
pulse_delay (us)

1
37500 (too fast)

2
18750 (too fast)

2.25
16666.6667 (works)

2.5
15000  (works)

3
12500  (works)

5
7500   (works)

10
3759   (works)

// Stepper motor run code with TMC2208 driver and LCD code
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Stepper.h>
// Define Pins for Step Motor Driver
#define stepPin 7  // define pin for step
#define dirPin 8   // define pin for direction
#define enPin 9    // define pin for enable ^^ Do I need this?

// Define Buttons for Speed and Direction
#define buttGo 10      // define pin for button input
#define buttSwitch 11  // define pin for button input
#define incSpeed 12    // define button for increasing speed
#define decSpeed 13    // define button for decreeasing speed

// Define LCD pinout
const int en = 2, rw = 1, rs = 0, d4 = 4, d5 = 5, d6 = 6, d7 = 7, bl = 3;  // Adapter Pinout
const int i2c_addr = 0x27;                                                 // Adapter pinout
LiquidCrystal_I2C lcd(i2c_addr, en, rw, rs, d4, d5, d6, d7, bl, POSITIVE);

/* Formulas for determining RPM
Assuming one step per pulse, delay is: wait = (μs/min)*(1/rpm)*(1/pulses per revolution) - overhead
Overhead = extra time it takes to run digitalWrite twice and loop
RPM = (steps per second)/(steps per revolution) * (60 seconds/minute)
step angle = 1.8 degrees ; 200 steps per revolution ; .005 revolutions per step
Solving for Steps Per Second: SPS = (RPM)/((REV_P_STEP)*(60 sec/min))

According to Notes:
  C0 = 15 * M_PI ; Motor X Circumference
  XSPR = 1 * (200 * 11) ; Motor X Steps per Rotation
  dVx = dS * (XSPR/C0) ; Desired X-Axis time from mm/s to x-axis steps/sec (dS represents desired x-axis speed)
  Assuming we use a button/knob, each increment/decrement would change the mm/s by 0.1
  So, to get the necessary pulse delay, increment/decrement by:
    dVx = 0.1 * (1 * (200 * 11))/(15*M_PI)

  Example: If we have an initial target rpm of 10, that gives us a dS of 10
  As such, dVx which is our speed in steps will be 10 * (1 * (200 * 11)) / (15 * M_PI)
  All of these variables are set globally
  wait = (microsecondsPminute)*(1/RPM)*(1/pulsesPrevolution) - overhead
  rpm / 60 = rps
  60 / rpm = spr
  (60 / rpm)/360 = spd
  ((60 / rpm)/360) * 1.8 = sps
***
Frequency = (RPM)/((Resolution/360)*60)
Resolution =  360/(Steps/Revolution)
For us, Resolution = 360/(200); so Resolution = 1.8**
Frequency = (RPM)/(0.005 * 60) = RPM/(0.3)
*
T_inc = incremental torque produced with each microstep
T_hfs = holding torque (full-step operation)
SDR = step division ratio (number of microsteps per full step)

T_inc = T_hfs * sin(90/SDR)
T_inc = 0.14 * sin(90/256)
T_inc = 0.00085902385
*/
float resolution = 1.8;
float rpm = 10;
float pulse_delay;  // Temporary starting value that will change after void setup
bool buttonState = false;
bool onState = false;

// Set up output types
void setup() {
  Serial.begin(9600);  // Change this baud rate to whatever rate the LCD screen runs on - should generally be 9600
  // Set up LCD screen
  pulse_delay = setRPM(rpm, resolution);
  lcd.begin(16, 2);  // set up the LCD's number of columns and rows:
  lcd.setCursor(0, 0);
  lcd.print("Current RPM: ");
  lcd.setCursor(12, 0);
  lcd.print(rpm);
  lcd.setCursor(0, 1);
  lcd.print("MOVE RIGHT");

  // Sets up buttons
  pinMode(buttSwitch, INPUT);
  pinMode(buttGo, INPUT);
  pinMode(incSpeed, INPUT);
  pinMode(decSpeed, INPUT);

  // Establish initials
  pinMode(enPin, OUTPUT);
  digitalWrite(enPin, HIGH);  // deactivate driver
  pinMode(dirPin, OUTPUT);
  digitalWrite(dirPin, HIGH);
  pinMode(stepPin, OUTPUT);
  digitalWrite(enPin, LOW);  // activates driver
}

// Revolutions per second should be able specified to the tenths
// Run code to continual
void loop() {
  // Read Buttons Being Pressed
  int pressSwitch = digitalRead(buttSwitch);
  int pressGo = digitalRead(buttGo);
  int pressInc = digitalRead(incSpeed);
  int pressDec = digitalRead(decSpeed);
  pulse_delay = setRPM(rpm, resolution);  //pulse_delay = (rpm * 200)/60;

  if (pressSwitch == HIGH)  // Moves motor Right (Counter-Clockwise)
  {
    if (buttonState == 0) {
      digitalWrite(dirPin, LOW);  // sets direction of the motor turning
      buttonState = 1;
      lcd.setCursor(0, 1);
      lcd.print("MOVE  LEFT");
      delay(500);
    }
    else {
      if (buttonState == 1) {
        digitalWrite(dirPin, HIGH);  // sets direction of the motor turning
        buttonState = 0;
        lcd.setCursor(0, 1);
        lcd.print("MOVE RIGHT");
        delay(500);
      }
    }
  }

  if (pressGo == HIGH)  // Moves motor
  {
    digitalWrite(stepPin, HIGH);  // This LOW to HIGH change is what creates the "Rising Edge" so the easydriver knows when to step.
    delayMicroseconds(pulse_delay);
    digitalWrite(stepPin, LOW);
  }

  if (pressInc == HIGH)  // Increases RPM
  {
    rpm = rpm + 0.1;
    delay(150);
    lcd.setCursor(12, 0);
    lcd.print(rpm);
  }

  if (pressDec == HIGH)  // Decreases RPM
  {
    rpm = rpm - 0.1;
    delay(150);
    lcd.setCursor(12, 0);
    lcd.print(rpm);
  }
}

// Function to get pulse delay time based off of inputted RPM value
float setRPM(float rpm, float resolution) {
  /*
  float temper = ((60 / rpm) / 360);
  float pulsetime = ((temper * resolution) * 1000000);
  1 rpm = 37500 us delay (too fast)
  2 rpm = 18750 us delay (too fast)
  2.25 rpm = 16666.6667 us delay
  2.5 rpm = 15000 us delay
  3 rpm = 12500 us delay
  5 rpm = 7500 us delay
  10 rpm = 3750 us delay
  */
  unsigned int pulsetime = (60000000 / (1600 * rpm));
  return pulsetime;  // Converts to microseconds
}

While moving (pressGo == HIGH) your high part of the pulse has a variable duration. How do you control the low part? -- Did you measure the generated signal, for example with a frequency counter or oscilloscope?

I made a quick table and it revealed that going from 3.0 to 3.1 in rpm crosses the "255/256 border" in pulse_delay. You might want to temporarily change your sketch to adjust pulse_delay directly to check this in detail.

@thebusybee I haven't been able to get my hands on a frequency counter or an oscilloscope, but I have used a multimeter just to see if there was an issue I was making with my hardware setup - which I don't think there is. I'll measure the generated signal to check that out!
What do you mean by crossing the 255/256 border? I have changed my pulse_delay directly in my pressGo if statement and it seems to work alright when changed directly.
Thank you for the quick response!

pulse_delay is a float, but you call delayMicroseconds() with it. This function expects an unsigned int according to the documentation, so the value is converted. The unsigned int uses multiple bytes, and values from 0 to 255 "use" only the least significant byte. Starting with 256, the next byte(s) carry other values than 0. That's what I mean by "255/256 border". -- Which range of values did you check concretely?

Thank you for the clarification on the byte "limit". I converted my pulse_delay variable to unsigned int since it makes sense to me that I should utilize it when using the delayMicroseconds() function. I also switched to the equation defined in my setRPM function to the one defined in this post. Using this equation I concretely checked rpms of 3, 5, and 10.

That change is fine, as it clarifies the working for the future reader, most probably your future self in some weeks. ;-) -- When I asked for the range tested, I meant the range of pulse_delay you checked out. Does the stepper run as expected? I would start with some high value (for low rpms, like 2000 µs) and decrease it down to some low value (for high rpms, like 100µs). If there is a problem with that mentioned border, you will still see this saw-tooth-like transfer function, the repetitions nicely matching multiples of 256. You might want to [edit] your question with a table.

Sorry about the confusion - I checked pulse delays from 37500 us to 3750 us and I noticed that it was running as expected up until the low value of around 18750 us delay which correlates to an rpm of 2. The stepper run stops running as expected after I start reaching lower RPMs/higher pulse delays. I also added a table of pulse delays and RPMs that I had tested to the original question as well. As for the saw-tooth-like transfer functions you are referring to the voltage displayed on an oscilloscope? I believe there is an issue with running accurately at lower speeds.

I cannot reproduce my table, I don't know where my calculations were wrong. So forget about the 255/256 border. -- Anyway, I cannot reproduce your values, too. For example, for rpm=2.5, temper=(60/rpm)/360=0.0666... and pulse_delay=(temper*1.8)*1000000=120000. But you list pulse_delay=15000. Please make sure that source and table results match, and correct.

The documentation says:

Currently, the largest value that will produce an accurate delay is 16383; larger values can produce an extremely short delay.

The value given to delayMicroseconds() seems to be processed by a modulo 16384 operation. That means that the value is divided by 16384, and the remainder of this division is the effective delay in microseconds.
If we apply this to the delays in your table, we get:

desired rpm
calculated delay (µs)
effective delay (µs)
effective rpm

1
37500
4732
7.9

2
18750
2366
15.8

2.25
16666
16666
2.25

2.5
15000
15000
2.5

3
12500
12500
3

5
7500
7500
5

10
3750
3750
10

One possible solution is presented in the same documentation:

For delays longer than a few thousand microseconds, you should use delay() instead.

You might want to consider to use both functions, depending on the necessary delay.

And then there is the other issue with the time when the output is low. Currently, it is determined by the time the code takes to quit loop(), do its internal looping, call loop() and your statements until the pin goes high again.
You might want to divide the pulse period in two halves and take control of this low phase, too.

Thank you for the response! For the second part of your answer, did you mean that I should split the pressGo motor run statement into stepPin High, (1/2 pulse delay), stepPin Low, (1/2 pulse delay)?
if (pressGo == HIGH)   {      digitalWrite(stepPin, HIGH);        delayMicroseconds(pulse_delay);      digitalWrite(stepPin, LOW);      delayMicroseconds(pulse_delay);   }
Here is my code for reference. I have also included another if statement such that if my pulse_delay is greater than that 16384 for the delayMicrosecond function, it uses delay() instead.

@jonathan Yes, you can go that route. Just be aware that the time to "turn-around" is currently and generally undetermined. You might want to measure it, for example with an oscilloscope or similar device. As long as it is small compared to the delays, you can consider to ignore it. Or you take it into account for the low phase.

For reference for any future readers who have had similar problems using a TMC2208 Stepper Motor - I have attached my annotated code to this answer for your use. In the annotation, I also include equations that can be used to determine spacings for a coiling setup.
// Stepper motor run code with A4988 driver and LCD code
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Stepper.h>
// Define Pins for Step Motor Driver
#define stepPin 7  // define pin for step
#define dirPin 8   // define pin for direction
#define enPin 9    // define pin for enable ^^ Do I need this?

// Define Buttons for Speed and Direction
#define buttGo 10      // define pin for button input
#define buttSwitch 11  // define pin for button input
#define incSpeed 12    // define button for increasing speed
#define decSpeed 13    // define button for decreeasing speed

// Define LCD pinout
const int en = 2, rw = 1, rs = 0, d4 = 4, d5 = 5, d6 = 6, d7 = 7, bl = 3;  // Adapter Pinout
const int i2c_addr = 0x27;                                                 // Adapter Pinout
LiquidCrystal_I2C lcd(i2c_addr, en, rw, rs, d4, d5, d6, d7, bl, POSITIVE);

/* Formulas for determining RPM
Assuming one step per pulse, delay is: wait = (μs/min)*(1/rpm)*(1/pulses per revolution) - overhead
Overhead = extra time it takes to run digitalWrite twice and loop
RPM = (steps per second)/(steps per revolution) * (60 seconds/minute)
step angle = 1.8 degrees ; 200 steps per revolution ; .005 revolutions per step
Solving for Steps Per Second: SPS = (RPM)/((REV_P_STEP)*(60 sec/min))

According to John Craig:
  C0 = 15 * M_PI ; Motor X Circumference
  XSPR = 1 * (200 * 11) ; Motor X Steps per Rotation
  dVx = dS * (XSPR/C0) ; Desired X-Axis time from mm/s to x-axis steps/sec (dS represents desired x-axis speed)
  Assuming we use a button/knob, each increment/decrement would change the mm/s by 0.1
  So, to get the necessary pulse delay, increment/decrement by:
    dVx = 0.1 * (1 * (200 * 11))/(15*M_PI)

  Example: If we have an initial target rpm of 10, that gives us a dS of 10
  As such, dVx which is our speed in steps will be 10 * (1 * (200 * 11)) / (15 * M_PI)
  All of these variables are set globally
  wait = (microsecondsPminute)*(1/RPM)*(1/pulsesPrevolution) - overhead
  rpm / 60 = rps
  60 / rpm = spr
  (60 / rpm)/360 = spd
  ((60 / rpm)/360) * 1.8 = sps
***
*Assume from measured diameter with calipers that it is 12 mm (Check 11.85 as well)
To get Spacings: V_extruder / RPM_rod
V_extruder = M_PI * Diam_extruder * RPM_extruder (in (mm*rev)/min)
RPM_rod = 13 rpm (set from original bought parts)
V_extruder = M_PI * 12 mm * X
Spacing = (M_PI * 12 * X) / 9.64507699 RPM
Spacing = 3.90863773 * X
For Spacings of 3 mm... 0.76753084 rev/min ~= 0.77 rev/min
For Spacings of 5 mm... 1.27921807 rev/min ~= 1.28 rev/min
For Spacings of 7 mm... 1.79090529 rev/min ~= 1.79 rev/min
*
y = 1.0715x + 2.6653
y = Voltage Setting
x = RPM
For Voltage Setting of 13, RPM = 9.64507699

T_inc = incremental torque produced with each microstep
T_hfs = holding torque (full-step operation)
SDR = step division ratio (number of microsteps per full step)

T_inc = T_hfs * sin(90/SDR)
T_inc = 0.14 * sin(90/256)
T_inc = 0.00085902385
*/
float resolution = 1.8;
float rpm = 3;
unsigned int pulse_delay;  // Temporary starting value that will change after void setup
bool buttonState = false;
bool onState = false;

// Set up output types
void setup() {
  Serial.begin(9600);  // Change this baud rate to whatever rate the LCD screen runs on - should generally be 9600
  // Set up LCD screen
  pulse_delay = setRPM(rpm);
  lcd.begin(16, 2);  // set up the LCD's number of columns and rows:
  lcd.setCursor(0, 0);
  lcd.print("Current RPM: ");
  lcd.setCursor(12, 0);
  lcd.print(rpm);
  lcd.setCursor(0, 1);
  lcd.print("MOVE RIGHT");

  // Sets up buttons
  pinMode(buttSwitch, INPUT);
  pinMode(buttGo, INPUT);
  pinMode(incSpeed, INPUT);
  pinMode(decSpeed, INPUT);

  // Establish initials
  pinMode(enPin, OUTPUT);
  digitalWrite(enPin, HIGH);  // deactivate driver
  pinMode(dirPin, OUTPUT);
  digitalWrite(dirPin, HIGH);
  pinMode(stepPin, OUTPUT);
  digitalWrite(enPin, LOW);  // activates driver
}

// Revolutions per second should be able specified to the tenths
// Run code to continual
void loop() {
  // Read Buttons Being Pressed
  int pressSwitch = digitalRead(buttSwitch);
  int pressGo = digitalRead(buttGo);
  int pressInc = digitalRead(incSpeed);
  int pressDec = digitalRead(decSpeed);
  pulse_delay = setRPM(rpm);  //pulse_delay = (rpm * 200)/60;

  if (pressSwitch == HIGH)  // Moves motor Right (Counter-Clockwise)
  {
    if (buttonState == 0) {
      digitalWrite(dirPin, LOW);  // sets direction of the motor turning
      buttonState = 1;
      lcd.setCursor(0, 1);
      lcd.print("MOVING  LEFT");
      delay(500);
    } else {
      if (buttonState == 1) {
        digitalWrite(dirPin, HIGH);  // sets direction of the motor turning
        buttonState = 0;
        lcd.setCursor(0, 1);
        lcd.print("MOVING RIGHT");
        delay(500);
      }
    }
  }
// Both of the next functions move the motor, but switches between Microseconds and Milliseconds in delay time to fit.
  if (pressGo == HIGH && pulse_delay >= 16383)  // Moves motor
  {
      digitalWrite(stepPin, HIGH);  // This LOW to HIGH change is what creates the "Rising Edge" so the easydriver knows when to step.
      delay(pulse_delay/1000);
      digitalWrite(stepPin, LOW);
  }

  if (pressGo == HIGH && pulse_delay < 16383)
  {
      digitalWrite(stepPin, HIGH);  // This LOW to HIGH change is what creates the "Rising Edge" so the easydriver knows when to step.
      delayMicroseconds(pulse_delay);
      digitalWrite(stepPin, LOW);
  }

  if (pressInc == HIGH)  // Increases RPM
  {
    rpm = rpm + 0.01;
    delay(150);
    lcd.setCursor(12, 0);
    lcd.print(rpm);
  }

  if (pressDec == HIGH)  // Decreases RPM
  {
    rpm = rpm - 0.01;
    delay(150);
    lcd.setCursor(12, 0);
    lcd.print(rpm);
  }
}

// Function to get pulse delay time based off of inputted RPM value
float setRPM(float rpm) {
  /*
  float temper = ((60 / rpm) / 360);
  float pulsetime = ((temper * resolution) * 1000000);
  1 rpm = 37500 us delay (too fast)
  2 rpm = 18750 us delay (too fast)
  2.25 rpm = 16666.6667 us delay
  2.5 rpm = 15000 us delay
  3 rpm = 12500 us delay
  5 rpm = 7500 us delay
  10 rpm = 3750 us delay
  */
  unsigned int pulsetime = (60000000 / (1600 * rpm));
  return pulsetime;  // Converts to microseconds
}

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


text:
Incorrect HEX code from DMM IR RS232
I have an Amprobe 38XR-A (sometimes seen as a meterman), these DMM's have a IR RS232 port on top and transmit a HEX code. Using the official cable I get a hex value of:

08000400500A0

I am attempting to read the IR RS232 via Serial1 of a pro-micro and display the output via Serial, but am getting an incorrect HEX code of:

6C666196665665F6793D

I have tried changing the resistor, in case it wasn't turning on/off fully with no change to the output (unless its a drastic change, then nothing is seen).
A buffer size of 15 appears to give repeatable results and is inline with the specification.
In an attempt for repeatability I have a test lead between the common and ohm port of the DMM.
Set-up:

Arduino Code:
const int BUFFER_SIZE = 15;
char buf[BUFFER_SIZE];

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

  while(!Serial){  }
}

void loop() {
  if(Serial1.available()){
    // read the incoming bytes:
    int rlen = Serial1.readBytesUntil("\r\n", buf, BUFFER_SIZE);

    // prints the received data
    Serial.print("HEX Data: ");
    for(int i = 0; i < rlen; i++)
      Serial.print(buf[i], HEX);
    Serial.println("");
  }
}

Additional links:
Output Codes PDF
DMM Manual
IR photodiode

edit

Original IR receiver circuit.

I find it hard to believe that the signal is not modulated as common IR TV remote control signals are. The only widely known exception I know of is the obsolete IRDA format used in Palm Pilots. I'm betting that the actual 83SW adapter contains one of these COTS ~48KHz all in one demodulator IR receiver.  Do you have an oscilloscope?

Also, it is not clear what data you received and what data you were expecting.  Can you edit your question to include both and clearly say which is which?

RS232 uses 10 bits, or more, for every byte ... you have to look at the binary data, not hex ... don't use serial input ... sample the raw data on the pin at regular intervals instead, then examine the bits

hex 6C666196665665F6793D is binary 0110 1100 0110 0110 0110 0001 1001 0110 0110 0110 0101 0110 0110 0101 1111 0110 0111 1001 0011 1101 ... there are a lot of 11 and 00 ... that may be an indication that the signal baud rate is lower than you think

@st2000 yes I have an oscilloscope and 83SW has very little inside, transistor, diode a couple of resistors and caps - will take a pic Monday. Also, I am after the 83SW output, so 08000400500A0

@jsotola When I sampled the raw pin, there was nothing regular and the datasheet (at the bottom of the post) states it's as HEX and a baud rate of 9600

Could it be that the thing you think is a photo sensitive transistor or photo sensitive diode inside a real 83SW could actually be a complex integrated circuit such as this device?  If you built a circuit using an ordinary photo sensitive transistor or diode and you view the photo sensitive device's output do you see what looks like an RS323 signal or do you see bursts of an about 48KHz signal?

I've added an image of the original PCB to the post


text:
Ideas for setting I2C device IDs
I am using I2C to communicate between a collection of ATtiny85s that are acting as controllers for various parts of a system and the "Main Brain" -- a RaspberryPi. Most of the ATtiny85s only have a couple of free pins left (usually Pins 1 and 2 -- the reset and the pin that can't be used for PWM) so I can't use something like a DIP switch to directly set device IDs. I'd rather not hardcode the device IDs when I push code to the tinys but I can't think of a good, simple, and reliable way to do it otherwise. Anyone here have a suggestion?

You could use the analog input on pin 1.
Have a table in your code to map voltage thresholds to I2C IDs.
Then build a voltage divider circuit as input that you can adjust with switches or by installing different resistors.

This is along the lines of what I was thinking. Maybe I could use the TinyDebugSerial to report the selected value as I adjust a variable resistor or something.

Someone just suggested I use a R-2R resistor ladder with a DIP switch to create a predictable and reliable analog value. If I can figure out the circuit, this seems like the way to go.

If you're going this route then maybe you should use a DS4303 or DS4305 instead of a full DAC.

I ended up going with a block of jumpers tied to different resistors to vary the voltage. I connected the jumper block to Pin 1 (so I could use Pin 2 for TinySerialDebug) and then used analogRead() to read the value of Pin 1 and map that to an set of I2C addresses.

Put the address in EEPROM. It's still "on the chip" but it can be programmed independent of the flash, and can be changed on the fly if deemed appropriate.

Can you give an example or a link to an example of how to program the EEPROM at "install time" separate from when I load my code on the ATtiny85?  I am using the Arduino IDE to do my programming if that makes a difference.

Blank EEPROM cells have a value of 0xFF, so if your code detects that it's using that address then it should enter a special mode where a I2C master can connect to it and tell it the new address, and then it can perform the actions described in the "EEPROM Data Memory" subsection of the "AVR Memories" section of the datasheet to write the new address to EEPROM and then begin normal operation.

Make sure you program the EESAVE fuse, so the contents of the eeprom are preserved when uploading new code.


text:
Reading a car mass air flow, volumetric air flow meter
I'm looking to build an air flow meter that will output in standard liters per minute. The cheapest sensors seems to be a car's Mass Air Flow sensor. I'm wondering if there is a way use  one of these MAF to measure air flow in liters per minute.
Essentially I need to measure a medical ventilator's air flow in order to calibrate it. The gas flow analyzers that are normally used are way too expensive and offer too many extra features that I don't need.
Thank You

You'll have to tell us more about the MAF.. a datasheet would be good. What protocol does it use to communicate with the host device?

Is a ventilator's MAF in a range where an automotive sensor would work accurately / reliably?

There's no reason that an MAF couldn't be used with an Arduino.  It's likely that the sensor will run on 12v and output an analog voltage from 0 - 12, so you might need to use a voltage divider with the Arduino.
See this Sparkfun article on implementing a voltage divider to scale down the 0-12 volt signal to 0-5v for the Arduino.

Does the sensor have to elecrtonic? How about a ball and tube flow-meter, say a lucite tube with a gradually expanding bore (harder) or constant bore just larger than a ping-pong ball, with a number of relief holes up the side (easier)? The higher the ball rises, the more air escapes through the relief holes. leaving less to support the ball while escaping around it.
You'd calibrate it with a positive displacement (piston) pump driven at values of (displacement/time) in the range if interest, and marking pen to record the ball position for each.

If you don't need to much precision, then use pulse counting from turbine wheel measuring device, that will give you the speed og air in the duct, multiply with duct area and you get the flow Volume.
Alternatively use a delta pressure sensor for the air speed measurement something like http://www.rcdrone.cl/producto/sensor-velocidad-aire-para-aviones/
Just some idea from
Lars Funder
Have a great day


text:
Teensy 4.1 / 4.0 When to use FlexPWM vs QuadTimer pins to strobe LEDs
I want to strobe 3 LEDs (at independent frequencies and duty cycles) via mosfets with a duty cycle of 0.05%-1% at a frequency range of 24-100 hz. I would like to hold 1% or better accuracy for both duty cycle and frequency.
The Teensy 4.x seems perfect with its amazing PWM frequency and resolution controls, and generous number of independent PWM timers.

For the purposes of my application, should I use pins with FlexPWM or QuadTimer? Does it matter?
I see that the numbering convention is X.Y, is there any functional significance when X numbers are in common (IE FlexPWM 1.0 and FLexPWM 1.1)?

See "Frequency" section of this page

I had cross-posted, and Paul Stoffregen answered in the Teensy Forum.
Pasting Paul's great answer here for posterity:

1: Really doesn't matter for 0.05% accuracy.
2:See "PWM Frequency" on this page.
The 3 pins identified as "FlexPWM1.0" (1, 44, 45) will always run at
the same frequency. If you want different PWM frequency, you would
need to choose pins from different groups.
More detail on how the hardware actually works can be found in the
reference manual. But usually that ends of being far too much
information. The timers are packed with a mind boggling number of
advanced features, which makes a steep learning curve if you want to
dive into how the hardware really works.
Most applications work fine by simply using analogWrite,
analogWriteResolution and analogWriteFrequency. Everything you've said
sounds like a pretty simple application that can be done easily with
these 3 functions. You're only looking for 9 bit resolution from
hardware than is natively 15 or 16 bits. Just use the easy functions
do the low-level work for you.


text:
Are these lcd and motor-shields stackable?
first of all, I'm kindly apologizing for asking such stupid questions, but as my electronic-knowledge is dramatically limited, you are my only hope to get my problem solved.
I'm pretty new to Arduino and my plans are to stack a lcd shield on a motor shield, which is stacked on the Arduino.
My setup would be the following:

Arduino MEGA2560
LCD-Shield http://www.sainsmart.com/arduino/arduino-shields/lcd-shields/sainsmart-1602-lcd-keypad-shield-for-arduino-duemilanove-uno-mega2560-mega1280.html
Motor-Shield http://www.sainsmart.com/arduino/arduino-shields/motor-shields/sainsmart-l293d-motor-drive-shield-for-arduino-duemilanove-mega-uno-r3-avr-atmel.html

My target is to enter specific values trough the LCD-shield (with its buttons) and to control a stepper-motor related to those.
Now to my question: Can I realize my project with the mentioned parts and are the two shields stackable (with head extentions on the motor-shield) without creating interferences?
Thank you very much for your time and answers in advance.
Best regards,
irie

No, it doesn't look like it.
The LCD board uses digital pins 4-10 and analog 0
The motor board uses digital pins 3-12 if all motors are used.
If you need to stack boards look for boards that use I2C since they can share a single data bus.


text:
Does Anemometer consumes power?
I planning to add an anemometer to my small solar weather station.
I designed this system to run from a single 3.7v rechargeable battery and a solar panel so I have to calculate in more power drain.
What I don't really understand is do these anemometers consume any external power or just give out a voltage by themselves?
This one doesn't even have consumption specified:
https://www.adafruit.com/products/1733
For this Supply voltage : 5V - 24VDC:
http://www.ebay.com/itm/JL-FSX2-4-20MA-0-5V-Output-Wind-Speed-Sensor-Wind-Speed-Transmitter-Anemometer-/331521148973?hash=item4d3033482d

If it runs on electricity it definitely consumes power, its only how much the real question is.
Since you are working with electronics I am going to assume that you have a multimeter, if you dont have one. Its about time you did, doesnt cost much and will save you a ton of time debugging.
Nearly every multimeter has an onboard ammeter (the accuracy will be mentioned in the instructions manual). You can use this to determine the current consumed, have a look at a tutorial from sparkfun on how to do this

It's anemometer. It usually works just as a generator, a low power one but still.

If you watch the video on the adafruit link, she mentions that its probably got a hall effect sensor in it, the power you are supplying is to power the sensor on board. So yes, it does consume power.


text:
Read Voltage at PWM off time, and Current at PWM on time
For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle). So i was thinking how i can do that, since i am using analogueWrite() function to give PWM output, i thought if i could access analogueWrite() fucntion, may be i could there insert the function of read_ADC_Voltage() during the LOW time, and read_ADC_Current() during the HIGH time.
Is my approach right ? If yes then can please anyone tell me how can i access and use this analogueWrite() function ? And if someone has any other idea to do the readings correctly, please suggest. I shall be grateful.

P.S I am writing it as an answer since my code wont fit in comment
I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs. My code looks like following:
    #include <PinChangeInt.h>
    #define pw 3
    int pwm;

    void setup() {
      // put your setup code here, to run once:
      pinMode(pw, OUTPUT) ;
      pwm_setup();             // Set PWM to a frequency of 62.5kHz

      PCintPort::attachInterrupt(pw,rise,RISING);    // call void rise() when PWM is HIGH
      PCintPort::attachInterrupt(pw,fall,FALLING);   // call void fall() when PWM is LOW

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      pwm = 127;                                                // 50% duty cycle
      pwm_on(pwm);

    }
    void pwm_setup()
    {

      TCCR2A = 0x23 ;
      TCCR2B = 0x09 ; // mode 7, clock prescale by 1
      OCR2A = 256-1 ;  // 256 clock periods = 16us per cycle
      OCR2B =0 ;
      TCNT2 =0 ;

    }
    void pwm_on(double)
     {
        OCR2B = pwm ;
     }

    void rise()
    {
      Serial.println("RISE");
    }

void fall()
{
  Serial.println("fall");
}

But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.
Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can you point it out please ?

Add a pin-change-interrupt (PCI) handler (See eg PinChangeInt at arduino.cc); clear the flag and enable the interrupt whenever you want to take readings, and disable that PCI after you have the reading.  As noted in the link, PCIs are available on all signal pins (possibly not on A6 and A7 on the 328), so are available on any of the PWM pins.

i tried to, but i am confused as the code isnt working as it is supposed to, in my opinion, so i posted my problem as an answer, as the code wont fit in comment box. Can you please tell what i am doing wrong?

I suggest that you copy your 'answer' to a new question.  I'm not going to evaluate that 'answer' here because use of comments for such evaluation is cumbersome -- comments can't be edited after their first five minutes -- and it does not tie into the stackexchange reputation system.  Anyhow, post that as a separate question and I'll be glad to answer.  Note, when you get another 5 points of reputation, you can start upvoting answers you find useful.  Also, you can accept answers that best address questions you ask.  Accepting and upvoting answers gives more people incentive to answer well.

i just did..here is the link to it.

No, in my opinion changing functions in the Arduino Core is not a good approach. You would have to change it back for any other project you are going to do and secondly, if you insert a function in the part where analogWrite is low it will result in a change in the duty cycle. Which may not be a big problem, but just don't.
My advice would be to use a timer to run a callback function every x seconds. Then in that function temporarily set the PWM to 0 and read your values. This is indeed not the most efficient approach, but we're talking about microseconds here... This approach is completely intterupt driven so you could run other things while it is running it's PWM and checking the voltage periodically.
It sounds as if you have gotten pretty far by yourself, so I'm not going to write you example code. You can a tutorial on how to use a timer to periodically call a function here.


text:
Arduino Yun C++ environment? Bridge + Cross-Compiler
I'm creating an XMPP chatbot for the Arduino Yun. However, I'm not too confident in the Python performance on such a low performance device and I'm much more comfortable with C++. Is there a C++ crosscompile environment available, and is there a port of the Bridge library to C++? Alternatively, documentation on how to interface with the ATMega using raw serial communication?

Even if compiling C++ on the openwrt of the yun is possible with the last release of the yun-openwrt you should make a yun build-chain. That makes you compile on you computer for the processor architecture of the embedded machine on the yun.
I have never done but you can find some informations about it in those links:
- https://github.com/arduino/openwrt-yun
- http://fibasile.github.io/arduino-yun-custom-buildroot.html
- http://fibasile.github.io/compiling-nodejs-for-arduino-yun.html
- https://github.com/arduino/openwrt-yun/issues/20
For the other question.. for sure you can read/write serial directly from the openwrt. You need to disable the Bridge library (there are a lot of post around the internet. one is this one see the Disabling the Bridge Script chapter) and manually handle the serial communication.
Hope it helps!

The Linux side of the Yun is just an OpenWRT installation. It has hardly been modified at all.
To cross-compile you will first need a Linux computer, or a Linux virtual machine.  Then you need to download the OpenWRT source code and configure it for the Yun (I think it defaults to the right settings).  Then you can build the whole OpenWRT image.  One side-effect of that is it compiles and configures a full cross-compiling environment for you.
You can then use that cross-compiling environment to compile your own code.


text:
Programatic FOTA (Firmware-Over-The-Air) upgrades with Uno R3
I have been searching for a way to upgrade the sketch on my Arduino Uno wirelessly (preferable WiFi, but not a must). Does the Uno support such function?
If not - are there any other boards that might support it?
Also, to further extend on the problem - I wouldn't want to upload a new sketch through the Arduino IDE but rather do it programmatically (trying to integrate it with a version management system of my own).

The "Particle"  (was Spark Core) is an Arduino compatible ARM processor with inbuilt WiFi that supports program loading from "the cloud" and data transfer to and from elsewhere also by WiFi. Not cheap but reasonable. Shop - lots of goodies

http://lowpowerlab.com/blog/category/moteino/wireless-programming/ supports OTA firmware upgrade, though not via WiFi.

There's two ways you can go about this - hardware and software.
To do it in software would mean writing a new bootloader that supported whatever wireless medium you chose.  The bootloader might end up quite large and thus restrict the size of sketch you are able to support.  It may also require advanced programming techniques in order to fit it into memory.  Not a task for a beginner.
Doing it in hardware is easier but more restrictive.  You need a wireless medium that can emulate a serial device including the ability to perform a reset of the Arduino.  There are bluetooth interfaces for the Arduino that can perform this kind of functionality, but I am not aware of anything WiFi or Ethernet that even remotely comes close.
There are Arduino boards available with this kind of bluetooth interface built in.
A possible third option is something in between - you have two Arduinos (or some other external MCU based system, like an ATTiny for instance), the "target" and the "programmer".  The "programmer" is what is connected to the wireless and accepts instructions and commands over the air.  It is then capable of putting the "target" into bootloader mode (reset it) and pass data through to its serial port for programming.  It does mean the "target" isn't directly connected to the wireless though, so it is up to the "programmer" to support whatever wireless functionality is needed and communicate properly with the "target" to get it to do everything it should.  There is no way to do FOTA to the "programmer" though, so you're back at square one if you want to reprogram that...

ESP series WiFi chips would be able to update an Arduino's software. But I am not aware it has been done yet.

This is possible using stock ESP8266 and Arduino components. My question addresses this and provides the relevant links I have found. The alternate to what I'm doing is to flash the ESP8266 with some alternate firmware e.g. ESPLink, NodeMCU or uPython. ESPLink seems purpose built for over the air updates, but I have no experience with these.

There are plenty of examples of Arduinos being used to reprogram Arduinos:

Using an Arduino as an AVR ISP (In-System Programmer)
Standalone AVR ISP Programmer Shield Kit
Atmega chip stand-alone programmer to upload .hex files
Atmega bootloader programmer

So the obvious choice here is to have two chips. One does the real work, the other one programs the first one, when required.
The "programmer" chip could be written to read from a disk file, accept data over Ethernet, WiFi or whatever. And it could be programmed to reprogram the target chip at a certain time of day, or on command.
In this system the "main" chip gets on with whatever-it-is it is doing, and the "programmer" chip just monitors its source of new code.

Does the Uno support such function? If not - are there any other boards that might support it?

I don't know of any boards that directly support that. These boards are generally built as educational tools, not as ready to deploy in the field as robust auto-upgrading devices. For one thing, keeping things cheap enough for students to purchase, perhaps one for each student in a classroom of 30, was one of the design criteria.

It makes little sense to use another Arduino for this, as they don't have the needed connectivity either.  Rather, use the connectivity (WiFi, BLE, whatever) processor to reprogram the Arduino... or just use the connectivity processor instead of the ATmega Arduino, since most of these devices have far better support for self programming and more resources for processing messages in general.

You can wire an ESP32-based board or module to your Arduino, and use https://vcon.io for a remote OTA. vcon firmware can act as an AVR (and not just AVR) programmer, and reflash your Arduino remotely.
Also, as a side-effect, you'll get remote control capability for your Arduino. https://dash.vcon.io cloud service gives you device dashboard and an API for remote control and OTA.
Disclaimer: I do represent https://vcon.io product.


text:
Compare const char * to const char
Using ArduinoJson I have assigned a value such as;
const char* id = root["id"];

in the original JSON id was "1"
if (strcmp(id, "1") == 0) {
    // this executes
}

I have an array of structs that I wish to compare the id against. The struct looks like;
typedef struct  {
   char id[2];
   ....
} Device;

I assign an id (1-9) into the struct id by
_cmd.id[0] = '0' + (++DevicesPtr);
_cmd.id[1] = '\0';
Devices[DevicesPtr-1] = _cmd;

where _cmd is of type Device. Devices is an array with up to 8 entries
Now I try to find a match in the devices using the JSON id
for (byte i = 0; i < DevicesPtr; i++) {
    if (strcmp(Devices[i].id, id) == 0) {
       // This code does not execute
    }
}

I can't seem to get a match I have also tried (Devices[i].id == id)

Strcmp is the way to go, but I'm not sure your code is giving away what the issue is, Mikaels answer is a more explicit version of what I imagine your code looks like. I presume you initialize DevicesPtr to 0 at some point? Mikael is also renaming your variables to more useful names another good idea : Could you post the code in full?

Try something like this:
typedef struct  {
  char id[2];
  ....
} Device;

const int DEVICES_MAX = 8;
Device Devices[DEVICES_MAX];

for (int i = 0; i < DEVICES_MAX; i++) {
  Devices[i].id[0] = '1' + i;
  Devices[i].id[1] = 0;
  ...
}

for (int i = 0; i < DEVICES_MAX; i++) {
  if (!strcmp(Devices[i].id, id)) {
  ...
}

Cheers!

You can't compare a char and a string.. How can you compare apples and bananas?
Now, you have two ways to do your job.
1) do as @Mikael Patel suggests, so convert your ids into strings. This is fine because it will allow you to deal with multiple chars ids.
2) a more efficient way to do this (note that this works with just SINGLE CHARS IDS) is the following one:
if (strlen(id) == 1) {
    for (byte i = 0; i < DevicesPtr; i++) {
        if (Devices[i].id == id[0]) {
           // This code will execute if ids match
        }
    }
}

Note that id should be exactly 1 char long, otherwise the whole comparison as you thought is meaningless
With this solution you don't need multibyte id char in the struct definition, so you can just define
typedef struct  {
   char id;
   ....
} Device;

and, in the code,
_cmd.id = '0' + (++DevicesPtr);
Devices[DevicesPtr-1] = _cmd;

Actually this can be improved further. The id field in the struct is not needed as the index is a function of the value (i.e. index = id - '1'). The test is simply that the index must be in [0..last_device] and last_device in [0..MAX_DEVICES-1]. A search is not really required if the id is ['1'...'9'].


text:
Arduino ethernet shield not responding to every request because it is busy
I have a simple HTTP server that monitors a serial port and responds to HTTP requests by sending the value. The serial port constantly outputs data, so that apart from a brief moment when the device is initializing the Arduino always has data available. Once a value is retrieved from the RS232 connection it is stored in a buffer. The buffer is overridden when new values are received.
Occasionally the server does not respond to a request. Monitoring through Chrome developer tools reports net::ERR_CONNECTION_RESET
Could it be that the Arduino is busy with processing the serial port when the connection request is made? What I find very difficult to understand is that once in a while the code below will display "Not available". This shouldn't happen because, as stated above, the buffer is always available.
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connection: close");
    client.println("Cache-Control: no-cache, no-store, must-revalidate");
    client.println("Pragma: no-cache");
    client.println("Expires: 0");
    client.println("Refresh: 5");
    client.println();
    client.println("<!DOCTYPE HTML>");
    client.println("");
    client.println("");
    client.print("Value: ");
    if (valueReady()) {
      client.println( getValue() );
    } else {
      client.println( "Not available" );
    }
    client.println("");
    client.println("");

The "Not available" message is really confusing because that should only occur when the Arduino starts. valueReady() will only return false when power is first applied.
The LEDs on the Ethernet shield do not indicate that the Arduino is being reset, but it seems as if the sketch is periodically restarting. Is it possible for a buffer overrun to cause the Arduino to reboot?

The delay was occurring because, in some cases, I was storing the RS232 data into a character array past the initialized length. It looks like it was causing the Arduino to reboot.

It's often a good practice to send debug information (flashing LED's or sending a string) at startup. The vaguest problems (, power issues and some memory issues) can be spottend this way.


text:
Can I use an Arduino and GSM breakout board for triangulation?
IS there a way for me to use cell towers to triangulate my location with an Arduino Uno and GSM breakout board? if so how?

What sort of accuracy are you after? If you're thinking within a set group , then no as the signal is too variable; if you're thinking in square miles + then yes! Just walking through the 'shadow' of a building will cause major signal level fluctuations.

A directional antenna with "steering" will be of some value in some situations, but 'city canyons' may render this useless (or worse :-) ).

While there are obviously limitations, the key question is if your module exposes cell identity and signal level information via an interface you can use.  And it would seem more useful if it can expose info for additional cells it is aware of, beyond the one it is actually using and when not engaged in handover.

what if i used a gps module? How accurate could I be?

new gps modules are really good, but the accuracy depends on many variables. number of satelites, weather. worst case can be kilometres, best case can be less than 1 meter... But if you have the choice go for gps. It does what excactly what you want...


text:
Obfuscate .hex file
I've wrote a code for arduino mega, and want to force it from copying (this is commerce project). How can I obfuscate .hex file before uploading to arduino?

I think you are looking for something like this


text:
How to interrupt a code after delay
I have a functionality on my mega 2560 to connect with other devices. Sometimes, devices can't answer. I don't want to wait for a longwhile. So, how can I interrupt the chunk of program after the specific amount of time?
My code for receiving messages is:
while (!(UCSR1A & (1<<RXC1)));

so, millis can't solve my problem because I haven't ability to check for conditional loops like that
if(currentMillis - previousMillis > interval) {

It's often better to mention why you would want to do such a thing. I'm guessing that you want to receive your messages every once in a while. It might be better to handle serial events in interrupts (for fastest receiving). Or to handle it in a timer interrupt (better timing).

The question might be better titled "How to break out of a loop with a timeout", since interrupts and delay have completely different meanings that you are using here.

OMG, I was stupid. I can just place millis in this while condition.

'if(currentMillis - previousMillis > interval) break;' may work as well. -- If the logic could become more complicated, a separate break statement for the conditions might make the code clearer.


text:
Arduino serial monitor first message
I'm connect arduino to my PC through serial monitor. Very common situation:
Serial.begin(9600);
delay(100);
Serial.print("Hello, World!");

But I always get an ¤ello, World!. How can I get the first symbol straight? I've tried on both unix & windows, mega & uno. I've also tried println, but with no happiness

What happens in you increase the delay?

@Gerben, is this an required option - to make a delay after build? Will try soon

Questions, questions: [1] What happens if you do a second Serial.print(<something>);? [2] What happens if you change the data rates (in code and Serial Monitor)? [3] If you change the first letter (H), does the displayed symbol change too? [4] If it does change, could you edit your question to include a list of half a dozen examples? The character you've shown is not part of neither the standard nor the extended ASCII tables. This suggests an extra byte is being sent or the Serial Monitor is adding the preceeding byte and decoding it along with the 'H'.

I had the same problem when were I sending data from the ptython script. First byte was alway lost. As a workaround I add unnecessery ser.read() before actual communication. ser was the name of the Serial instance.

@chaaarlie2: ‘¤’ is U+00A4. It's a single byte in quite a few 8-bit character sets, including Latin-1, several other ISO-8859 variations, and Windows-1252.

@Edgar Bonet: yes, it appears in the UCS as a replacement for the original ASCII character in most fonts, but it's still not an original ASCII character. Yes, it's unlikely that the serial monitor is taking a double-byte letter, and it's probably the monitor's font representation of U00A4, but there's nothing wrong with being thorough. An answer from the OP to my fourth question in my original comment would rule out any ambiguity by mapping sent characters to received characters.

@chaaarlie2: I'm not saying it's an ASCII character. It's not. I'm not questioning the usefulness of your questions either. I'm only pointing out that in your sentence: “The character you've shown is not part of neither the standard nor the extended ASCII tables.” the part I emphasized is incorrect. At least if you use “extended ASCII tables” in its usual meaning of “ASCII-compatible 8-bit character sets”.

See the following article:
http://www.arduino.cc/en/Main/ArduinoBoardNano
See the section at the bottom called:
Automatic (Software) Reset
Basically, one has to delay for 1 second (at least) after initializing the serial port before you can read data.  It seems that the Arduino makes an assumption that after the serial port is initialized, what may happen next is a request to load a program.  As such, it looks for a period of time (I guess up to a second) for a string of magic characters that indicate a program load.  If it doesn't find those, then it starts to behave as you would expect ... but only after it times out looking for a program load.

That delay only applies to the host.  The sketch does not start until the bootloader surrenders control.

I'd have to be pretty quick to connect my serial monitor to see immediate terminal output from my program, if that output uses the same USB I used to load the program. You can test this by resetting the Arduino so it will repeat the output and see if you get a clear message this time. So I leave a couple of seconds' delay in the code to let the slow human catch up. Most of my devices announce their name and code-version on the serial I/O and flash a quick "I'm here" on the LED (if I chose to attach one) when they first wake up:
const char IdString[] = "Hello.cpp: $Revision: 1.3 $";

void setup(void)
{
   Serial.begin(57600);            // open serial port

   // Identify to the terminal
   delay(2000);
   Serial.println(IdString);       // hello (terminal)

   // Init LED pin
   pinMode(LED_PIN, OUTPUT);
   digitalWrite(LED_PIN, LOW);

   nblink(4);                      // hello (LED)
   ...

The Uno resets itself when you open the terminal.

Oh, yes, of course. I'm too used to bare chips without auto-reset implemented.

This is more a wild guess than a real answer... Assuming your terminal
is using a character set more or less like ISO-8859-1 or Windows-1252,
then you are receiving 0xA4 when you expect 0x48. My guess is that the
very first start bit got lost somehow.
Here are the serial port waveforms corresponding to the expected and
received bytes. ‘S’ and ‘T’ are the start bit and stop bit respectively.
The data bits are sent least-significant first. The idle state is HIGH:
• ‘H’ = 0x48 = 0b01001000
────┐               ┌───┐       ┌───┐   ┌──────
    │ S   0   0   0 │ 1 │ 0   0 │ 1 │ 0 │ T
    └───────────────┘   └───────┘   └───┘

• ‘¤’ = 0xA4 = 0b10100100
────┐           ┌───┐       ┌───┐   ┌──────────
    │ S   0   0 │ 1 │ 0   0 │ 1 │ 0 │ 1   T
    └───────────┘   └───────┘   └───┘

You can see that, if you remove the start bit from the first waveform,
you get exactly the second one. I do not know what may be the cause of
this though.


text:
Convert string plus hexadecimals to array of hex:
I have a string which I send to the arduino using serial monitor. Something like that:
my specific string 0x0F 0x2C 0x98 0xBC

How can I parse this string in the arduino to get an array of hex values:
0x0F 0x2C 0x98 0xBD

? There are two prerequisites:

All hexadecimal starts with #
The size of hexadecimal is 2. No 0x111 or '0xbbb'

Do hexadecimals start with a #, as you wrote in the text, or with a 0x, like in the example?

It would be easier to send decimal numbers over the serial and read them as so. After that you can read them from the array as HEX values?
If you have the possibility to change whatever is sending through your serial.

How can I parse this string in the arduino to get an array of hex values:

There are a few standard library (stdlib) functions that can help you with that. Below is a snippet:
char buf[] = "0x0F 0x2C 0x98 0xBD";
uint8_t val[4];

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

  char* bp = buf;
  int i = 0;
  do {
    char* ep;
    val[i] = strtol(bp, &ep, 16);
    Serial.println(val[i], HEX);
    bp = ep;
    i += 1;
  } while (*bp != 0);
}

void loop()
{
}

Cheers!

You can try reading each character and convert it to hexadecimal representation.
I suppose you wanna 1 byte each value in hexadecimal representation, so, let's start.
For example the string "0x25", ignore the 0x and read the '2' and save it into a char variable. Same for '5';
char highBits = '2' - '0'; // convert to decimal representation
char lowBits  = '5' - '0';

byte = (highBits << 4 | lowBits);

Now, save it inside you array. Make sure you check if the value is one of the possible letters in hexadecimal and convert it properly (A=10 and so on).
Just include an if statement if it is a letter and convert it.


text:
Difficult between atmega328 & atmega2560 when coding & compiling in a pure c
I have an arduino uno with atmega328p controller.
I found the code to deal with some specific uart protocol, named mdb: https://github.com/Bouni/MateDealer/tree/master/arduino
But it's compiled just for atmega2560 controller: https://github.com/Bouni/MateDealer/blob/master/arduino/makefile#L42
If I replace it by atmega328p or atmega328, I get the error:
asiniy@misha:~/projects/MateDealer/arduino$ make all

-------- begin --------
avr-gcc (GCC) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Compiling: main.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=main.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/main.o.d main.c -o main.o

Compiling: usart.c
avr-gcc -c -mmcu=atmega328 -I. -gdwarf-2   -Os -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wa,-adhlns=usart.lst  -std=gnu99 -DF_OSC=16000000 -MD -MP -MF .dep/usart.o.d usart.c -o usart.o
usart.c:25:40: error: ‘UBRR1H’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                        ^
usart.c:25:49: error: ‘UBRR1L’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                 ^
usart.c:25:58: error: ‘UCSR1B’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                          ^
usart.c:25:67: error: ‘UCSR1C’ undeclared here (not in a function)
     { { { {}, 0, 0 }, { {}, 0, 0 } }, &UBRR1H, &UBRR1L, &UCSR1B, &UCSR1C },
                                                                   ^
In file included from usart.c:14:0:
usart.c: In function ‘USART0_RX_vect’:
usart.c:185:5: warning: ‘USART0_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_RX_vect){
     ^
usart.c: In function ‘USART1_RX_vect’:
usart.c:197:5: warning: ‘USART1_RX_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_RX_vect){
     ^
usart.c:203:12: error: ‘UDR1’ undeclared (first use in this function)
     data = UDR1;
            ^
usart.c:203:12: note: each undeclared identifier is reported only once for each function it appears in
In file included from usart.c:14:0:
usart.c: In function ‘USART0_UDRE_vect’:
usart.c:233:5: warning: ‘USART0_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART0_UDRE_vect){
     ^
usart.c: In function ‘USART1_UDRE_vect’:
usart.c:253:5: warning: ‘USART1_UDRE_vect’ appears to be a misspelled signal handler [enabled by default]
 ISR(USART1_UDRE_vect){
     ^
usart.c:261:31: error: ‘TXB81’ undeclared (first use in this function)
                 UCSR1B |= (1<<TXB81);
                               ^
usart.c:266:9: error: ‘UDR1’ undeclared (first use in this function)
         UDR1 = data;
         ^
usart.c:269:20: error: ‘UDRIE1’ undeclared (first use in this function)
     UCSR1B &= ~(1<<UDRIE1);
                    ^
make: *** [usart.o] Error 1

I've tried to play with compilers (default is gnu99) and so on, but with no success. Why I have this trouble? How can I compile this code for upload it to arduino?

I'm the author of the MateDealer project and I never had the intention to port it to other boards than the Arduino Mega2560!
Ignacio Vazquez-Abrams is absolutely right, the Arduino Mega2560 is the only board with more than 1 serial port (Yes there is the Due and the Leonardo, but those would require major changes to the code).
The fastest way to get the code running is by using a Mega2560, but be warned, the code might be bugy as hell ;-)

The '328 only has a single USART. You will need to remove all references to USARTs beyond the first as well as the numeric suffix from the USART register names in order to get it to compile.

So, do you mean that I can't read data from MDB protocol and send it to the serial port of my computer to read it in the display?

If you require more than one USART to do so then no, you can't. You could try a serial UART, but this is beyond the scope of this question.

Can I use one usart for connect mdb and the second one for connect to serial of my computer?

Again, you don't have 2 USARTs.

SoftwareSerial library give me ability to  connect by 2 uarts, but not in the same time. I need to stop 1st usart, then run 2nd. How do you think, can I implement something like this in pure c?

You do have one hardware USART, as an uplink to the PC.

So, can I use one hardware UART to connect to the computer, and another one to connect to mdb?

You still only have one hardware USART. You will need to use a software UART as well.

So, can I implement connection from uno both to computer and mdb? Just yes or no, please


text:
Error with Arduino/Processing Serial Communication
I am relatively new to both Arduino and Processing and I have been working on a code that utilizes serial communication between the two. My Arduino code is reading and printing values from a piezo sensor and then sending the values to Processing, which sketches certain shapes based on the values. The code has worked previously, but for some reason it is no longer working. Everything compiles, but when I run the Processing code the sketch window is empty and remains empty. A few times the "error, disabling serialEvent()" showed up, but I just unplugged my Arduino board, closed out the programs, and restarted everything. The error no longer shows up, but my Processing sketch is still not displaying on the screen. Can someone please let me know what is wrong with my code? I really appreciate the help.
Arduino Code:
int ledPin = 13;
int knockSensor = A0;
byte val = 0;
int statePin = LOW;
int THRESHOLD = 5;
int sensorReading = 0;

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

void loop() {
 sensorReading = analogRead(knockSensor);

  if(sensorReading > 0){
   Serial.println(sensorReading, DEC);
   delay(100);
  }
}

Processing Code:
import processing.serial.*;

Serial port;

int centerX = 550;
int centerY = 400;

float val;
float ellipseX;
float ellipseY;
float ellipseW;
float ellipseH;
float ellipseXX;
float ellipseYY;
float ellipseWW;
float ellipseHH;
float lineX;
float lineY;
float lineXX;
float lineYY;

void setup(){
  background(255);
  size(1100,800);
  frameRate(10);
  smooth();

  String portname = "/dev/tty.usbmodem1411";

  //String portname = Serial.list()[0];
  port = new Serial(this, portname, 9600);
  println(Serial.list());
  //port.bufferUntil('\n');
}

void drawEllipse(float val)
{
  if(val > 0 && val < 50)
  {
    ellipseX = random(540,560);
    ellipseY = random(390,410);
    ellipseW = val + 10;
    ellipseH = val + 10;

    stroke(0);
    fill(random(255), random(200,255));
  }
}

void drawLines(float val)
{
  if(val > 50 && val < 70)
  {
    lineX = random(500, 600);
    lineY = random(360, 440);
    lineXX = random(500, 600);
    lineYY = random(360, 440);

    stroke(0);
  }
}

void drawEllipse2(float val)
{
  if(val > 70 && val < 120)
  {
    ellipseXX = random(460, 640);
    ellipseYY = random(330, 470);
    ellipseWW = val + random(20);
    ellipseHH = val + 10;

    stroke(0);
    fill(random(50, 100), random(50, 100), random(50, 100), random(220, 255));
  }
}

void serialEvent(Serial port)
{
  String inString = port.readStringUntil('\n');

  if (inString != null)
  {
      val = Float.parseFloat(inString);
  }

  drawEllipse(val);
  drawLines(val);
  drawEllipse2(val);
  println(val);
}

Nevermind, resolved!

It seems like you need to do some basic debugging:

Put a println() in setup. If this does not appear, you have a major problem talking to the Arduino board.
Put a println() statement in the loop() that prints out the sensor reading. That should separate hardware problems from software defects.

Try using this code and run it on your Arduino
void setup() {
   Serial.begin(9600);
}

void loop() {

Serial.print('hello world');
}

After uploading the code open the serial monitor and see if it shows the string 'hello world' and make sure that the baud rate of the serial monitor is set on 9600. If nothing shows this could mean that there is something wrong with your Arduino board.

Serial.print('hello world'); is not correct. It should read: Serial.print("hello world"); and preferably: Serial.println("hello world"); Check out the difference between single and double quotes in C/C++.

oh sorry i wanted to use double quotes but i wrote it wrong :( @NickGammon


text:
ATTiny85 Interrupt id vs pin when programming with Arduino
I am using an Arduino Uno with the Arduino as ISP sketch to program an ATtiny85.
I followed this tutorial to set up to program the ATtiny, and successfully got it to run Blink and an interrupt-free version of my program.
I then added an interrupt triggered by a button and got it working on the Arduino Uno (with a software debounce in the ISR). Now I want to run that sketch, with appropriate pin changes, on the ATtiny. Which pins correspond to which interrupt IDs for attachInterrupt()?
Or can I not use attachInterrupt()? If I can't, how do I do set up an interrupt on an ATtiny85?

attiny is kind of a piece of crap. Get arduino-tiny instead.

@IgnacioVazquez-Abrams attiny is kind of a piece of crap. I assume you refer to the device? If that is the case then how does an Arduino core change anything? The "instead" statement is what confuses me.

No I think Ignacio refers to the attiny library that is referenced by the tutorial.

I am indeed talking about the extension module for the IDE.

In arduino-tiny you can use the constant EXTERNAL_INTERRUPT_0 for INT0 at physical pin 7

@Gerben - Got an implementation example?

attachInterrupt(EXTERNAL_INTERRUPT_0, blink, CHANGE);

You can setup interrupts on the Attiny with some different code, but it works the same way. It's important to note that PIN Change Interrupts are triggered at BOTH Rising and Falling Edge
Pins:

Using the Arduino-Tiny Cores
Below is a sample code which used a Pin Change Interrupt on PB1 which switches an LED on and off on PB4.
//Includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define INTERRUPTPIN PCINT1 //this is PB1 per the schematic
#define PCINT_VECTOR PCINT0_vect  //this step is not necessary
#define DATADIRECTIONPIN DDB1 //Page 64 of data sheet
#define PORTPIN PB1 //Page 64
#define READPIN PINB1 //page 64
#define LEDPIN 4 //PB4

#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) //OR
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) //AND

/*
 * Alias for the ISR: "PCINT_VECTOR" (Note: There is only one PCINT ISR.
 * PCINT0 in the name for the ISR was confusing to me at first,
 * hence the Alias, but it's how the datasheet refers to it)
 */

static volatile byte LEDState; //variable used within ISR must be declared Volatile.

void setup() {
    cli();//disable interrupts during setup
    pinMode(LEDPIN, OUTPUT); //we can use standard arduino style for this as an example
    digitalWrite(LEDPIN, LOW); //set the LED to LOW
    LEDState = 0; //we use 0 for Low state and 1 for High
    PCMSK |= (1 << INTERRUPTPIN); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
    GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

    DDRB &= ~(1 << DATADIRECTIONPIN); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
    PORTB |= (1<< PORTPIN); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
    sei(); //last line of setup - enable interrupts after setup

}

void loop() {
  // put your main code here, to run repeatedly:
  //If you connect a debounced pushbutton to PB2 and to VCC you can tap the button and the LED will come on
  //tap the button again and the LED will turn off.

}

//this is the interrupt handler
ISR(PCINT_VECTOR)
{
  //Since the PCINTn triggers on both rising and falling edge let's just looks for rising edge
  //i.e. pin goes to 5v
  byte pinState;
  pinState = (PINB >> READPIN)& 1; //PINB is the register to read the state of the pins
  if (pinState >0) //look at the pin state on the pin PINB register- returns 1 if high
  {
   if (LEDState == 0)
   {
    digitalWrite(LEDPIN,HIGH); //you can use Arduino Code or LowerLevel Code to write to the register
    LEDState = 1;
    }
   else
   {
    digitalWrite(LEDPIN,LOW);
    LEDState = 0;
    }
  }

}

If you're going to be using the ATTiny85, I highly suggest you read through the data sheet to understand better how to program these chips at a lower level of code....It took me a while for it to start to make sense.

The ISR should be PCINT0_vect, see the include file iotnx5.h. #define PCINT0_vect _VECTOR(2).  Or at least, that is how it is in my distribution.

Why use PCINTn, when there is INT0 on PB2?

@NickGammon you're correct. I had some Alias defined in the code that I forgot to include. (Pun intended).I updated my answer.

@RSM INT0 is the timer 0 interrupt..not the pin change interrupt(PCINTn). AttachInterrupt in Arduino is a Pin Change Interrupt.

Interrupts which occur because of a timer that affect a pin happen on OCnx pins. INT0 is a hardware input interrupt, specific to that pin, read through the interrupt.h file in avr-gcc. also you should look at this look closely at pins 2 and 3, which arduino uses as interrupts and see that it is INT0 & INT1 respectively. Also you should take a look at the arduino core files, like WInterrupts.h and see it uses INT0, PCINTx is a group of pins

@RSM we're talking about Attiny85 Chip. INT0 is a level change interrupt which can be hardware programmed to trigger on Rising Edge OR Falling Edge and PCINTn is a Pin Change interrupt which triggers the ISR on BOTH Rising and Falling edges. INT0 also has it's own ISR.

PCINTn is a WHOLE REGISTER PB0 - PB5, i.e. you would have to pick out which pin had a trigger in the ISR, more time wasted in the routine, also all interrupts are level change or edge triggered, don't see your point??? I also know its the t85, the WInterrupts.h for tiny libraries also uses INT0. Hardware interrupts can be triggered on change too. To reiterate this AVRfreaks post by clawson #2, the interrupt occurs at a change, or on the edges. INT0 is a dedicated interrupt? where is the confusion

@RSM  no confusion. You're totally wrong about the register. Setting the PCMSK register enables only the pin(s) you want to allow to call the interrupt. Not ALL pins. Yes, all of those interrupts call the SAME ISR. So, if you have PB0 - PB5 all as interrupts enabled, then I think you're using the wrong chip for your application. In my example only PCINT1 causes the ISR to be called. It is called at BOTH rising edge and falling edge, so you may need to check if the Pin is High Or Low within the ISR. Checkout the data sheet chapter 9 on interrupts.

@GisMofx - I can see this is going to go in circles, I'm right, you're right... Lets leave it at that. For simplicity I would use INTn first. Your answer is good for pointing out another way  though. also add #include <avr/interrupt.h> if in the arduino ide.

@RSM Thanks. Ok. But I personally don't use INT0 on the Attiny because that pin is used for I2C/USI/SPI. Yes you're also correct you need the #include for interrupt

@GisMofx:  May I suggest you rework your answer to provide a complete, compilable example? Also move your comments about the mask into it to clarify. You use (1 << INTERRUPTPIN) in some places, but cbi(DDRB, DATADIRECTIONPIN) in others, which is a bit inconsistent. How about DDRB &= ~(1 << DATADIRECTIONPIN) ? You might also want to mention the difference between pin-change interrupts and external interrupts.

@NickGammon Thanks for the Tip. I've added a full sample code that compiles which uses an interrupt to turn an LED on and off.


text:
Can an L293D motor driver shield do microstepping?
I bought a L293D motor driver shield and have used it with a pre-made sketch for driving a pair of stepper motors, but I'm not familiar with its capabilities.
The sketch I've used so far doesn't use microstepping when it's set up for this shield (though it does use it with the Adafruit shield).
I've done some searching, and it's not clear if the L293D chips on the shield can do microstepping, and if so, how.
Are L293D chips (and thus the motor driver shield that uses them) capable of microstepping? If so, how can I add this capability into my sketch?

See Microstepping with Arduino - if that helps maybe post an answer summarizing what you found.

It would be more accurate to say that it can be used as part of a microstepping system, though it's probably not a good choice for any use today.
The L293D is merely an (effectively obsolete implementation of an) H-bridge, not a stepper motor sequencer, hence it is no more capable of autonomously driving a motor in full or half step mode than it is of microstepping - it can only do any of these when it is controlled by a sequencer, such as an L297 chip, or software running on an Arduino's processor.
Microstepping requires partially actuating the coils to interpolate between the angular positions which would be achieved by activating each in turn fully.  It can be thought of as a proportional extension of how half-stepping uses actuating both coils at the same power to achieve a halfway in between position, only now the coils are actuated at different power levels to achieve finer gradations of position, though achieving accurate interpolation requires care as the relationship is not linear.
Modern power electronics no longer use variable analog drivers, as these convert the unused power to heat.  Instead, the goal is to use switches which come as close as possible to only ever being fully on or fully off.  Reduced driver power is achieved by pulse width modulating the switch, varying the average amount of power delivered to the load over a short period of time.  In a stepper motor setting, this on-off modulation can be done to achieve microstepping and or also to achieve current regulation when a many-times-rated-voltage supply is used to allow overcoming winding inductance at high step rates.
The L293D (and its larger cousin the L298) are quite inefficient bipolar transistor bridges (they aren't very good switches compared to MOSFETs), and should probably not be chosen for new designs today.  They are, however, capable of being used to microstep a motor when actuated by a sequencer which pulse width modulates the phase signals.
Adafruit, who appear to be the original creators of this shield design, have in fact published microstepping driver code for their L293D board on github.
https://github.com/adafruit/Adafruit-Motor-Shield-library
Given that the ebay seller you link to as the source of the board is using Adafruit's own schematic on their product page, it's a bit unclear why your software is differentiating between this board vs an Adafruit one, unless by the the Adafruit board you mean their V2 shield.  The V2 design uses a more efficient TB6612FNG FET bridge, but of more relevance to microstepping offloads the sequencing task from Arduino software to a PCA9685 chip which is apparently capable of microstepping (as well as simpler modes) by itself.  Depending on the computational load and/or your  level of determination, you may be able to get the ATmega microstepping the L293D in the context of your overall project.

Not directly. The L293D is a digital H-bridge chip. L293 series devices allow you to supply enough power for small motors, and the "D" model has internal protection diodes. There are other ICs and breakout boards that are designed specifically for microstepping. Here are a few options...

The SparkFun EasyDriver ($14.95) will probably be the quickest solution.
There are a variety of stepper driver ICs on the market with a wide range of power ratings. For instance, ST makes the L6219 ($4.86) and ON also makes several versions of the LB1847 ($4.19-$6.90). TI also makes a few.

Datasheets will typically say whether a driver is capable of microstepping at the beginning. Just make sure the driver you choose is capable of handling the stall current of your stepper.
Are your steppers unipolar (6+ wires) or bipolar (4 wires)? That may make a difference in how you wire them, although some unipolar motors can be driven as if they were bipolar.

No.  There's a fundamental misunderstanding in this answer.  Microstepping is not practically implemented via analog circuitry, rather it is done in the time domain with switches that are always either fully on (to the best of their ability) or fully off.  As the L293 is merely a bridge, with no chopping or other current control of its own, the ability to microstep - or not - depends on what is driving it.  That said, the L293, like any bipolar driver has internal losses that make it a severely obsolete part!

@ChrisStratton, I am fairly new to SE. Can you recommend changes to improve the answer? From my understanding, a microstepper approximates two out-of-phase sinusoids. With that assumption, given a square wave generated from an L293D, it could be theoretically possible to build an analog circuit that would convert a square wave to a sine wave. The problem is that it would be difficult to create such a circuit that would work correctly at more than one frequency.

No.  Do not try to convert the digital output to analog - that way only leads to losses.  The key concept to grasp is that microstepping is ultimately about a time average over short periods of time.  It does not have to be achieved by an analog circuit at all.  Rather it can be (and usually is) done by purely digital means, modulating the on-time of a purely on/off switching device.  Anything other than an on/off switch converts unacceptable amounts of power to heat when it is "partially on" - but a time average of on and off does not, except in the switching transition itself.

@ChrisStratton, that makes sense. So, should I stuff about adding analog circuitry, delete this answer attempt completely, or just leave it as is?

Unclear.  The L293D is a rather disappointing device, but the problem it (sort of) solves is different part of the system than where micro stepping would, or would not, be implemented.  It is a bridge, while microstepping is implemented in the bridge controller (which is probably also the current regulating chopper).

Most of the micro-stepping circuits I am familiar with are hybrids (not purely digital). The current from each h-bridge is sensed (usually with a current-sensing resistor) and fed back to an analog comparator. This is compared to the output of a DAC (digital to analog converter) which outputs a voltage proportional to the desired current for the coil for the micro-step. The comparator output normally resets a flip-flop which is part of the digital timing circuit for the chopper-drive. The analog input used to set the drive-current is often the reference voltage for the DACs.


text:
What's the best way to control a USB-powered desk light
I recently bought a USB-powered desk light. Is it possible to control (turn on/off) it with the Arduino Uno? The desk light has 3W so needs 600mA.

Should I connect the USB wire with the 5V pin of the Arduino (which can spend up to 800mA) or should I use an external USB power supply ?
How to control the light when using an external USB power supply ?

Use a TIP120 Darlington transistor to switch the current.
This webpage has a detailed guide. http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/
Use the example with the light bulb - no diode is needed in your case.

What isn't explicitly mentioned here, but far more important, is that the device needs its own power supply.  It should not be connected to either the output of the Arduino's regulator, nor (at least not properly) a USB port to which the Arduino is connected.  The one exception might be if you have a higher current USB "power supply" which is not a computer.

You have a couple options here. The main idea is that you're going to add a switch to the light's circuit and that switch will be controlled by the arduino. It's important that you keep the electronics for the light and the electronics for your arduino separate, 600mA will damage your arduino which no one wants. You can power the light and arduino from the same power supply, make sure it can handle the power draw though.
To actually switch the circuit you could use an NPN transistor as mentioned above, with the lamp's - terminal flowing into the C pin, an arduino GPIO pin connected to the B pin and the E pin grounded. When you set your arduino's pin HIGH the transistor will allow current to flow and light up the lamp.
Another option that actually physically separates the circuits is to use an opto-coupler. They're little IC's that serve this exact purpose. The have a light and a light sensitive transistor inside them, so when the light illuminates, the transistor allows current to flow. In your case, you would hook up an arduino pin to the + pin on the light side of the coupler and ground the - pin. Then connect your lamp in the same to the other side, +5v into the + pin on the transistor side and the lamp's positive terminal to the output pin. Again, when the arduino pin goes HIGH, the lamp will light up.

Put the lamp on the collector side.

@geometrikal You're correct, I was thinking that the transistor would come before the lamp but I suppose it should be placed after the lamp.

yep, cause you need V_BE to be saturated

power lamp from 5v source ( not from the arduino 5v port, but could be spliced into the same line powering the arduino or use a hub )
use a transistor to switch the usb 5v line

connect the base pin (and resistor) of the transistor to any arduino digital out pin

Actually, if you are going to do it that way, use an NPN transistor and switch the ground line.  But there are more issues.  For example, the light should not be powered through the Arduino's regulator.


text:
Arduino can't create file in sd card
I need to write and read some data from SD card. I link SD card(LC STUDIO) to Arduino (UNO). I use this link for create my project. In first day I don't have any problem and data correctly save to file. But now my circuit isn't work nicely. When Arduino is running the sketch I don't saw any error message.But when I link the SD card to my laptop, I don't saw any file on card!!
The code is here:
#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

File file;

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

  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT);

  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
  }
  Serial.println("card initialized.");
  //creating file
  file = SD.open("test.txt",FILE_WRITE);
  file.close();
  //write data to file
  file = SD.open("test.txt",FILE_WRITE);
  if(file){
    file.println("OK!!");
    file.println("1");
    file.println("2");
    file.println("3");
    file.println("OK!!");
    file.close();
  }
}
void loop()
{
}

Welcome to Arduino SE! Can you please add more information to your post? We can't help you much here. What have you tried? Has anything changed?

Try using one of the SD library examples unchanged (at least beyond making sure chip select, etc are correct) to verify the hardware before you modify it in other ways.

First, are you running the board off of USB power from your computer? If so, can you open the serial monitor to see if things are running correctly? If you aren't, the SD card can be picky if your board is running on battery, if the power drops, your SD card can no longer be written or read from.

Seems that last time I had this issue, simply replacing the battery on my datalogger board fixed the issue

Thank you all...
I found solution for my problem.
The circuit and the sketch isn't any problem. But I saw this and I think problem is because of LC Studio's SD card. In previous circuit I connect 5v pin of SD card to 5v pin on arduino. But now I disconnect that and connect 3v3 pin on card to 3v3 on arduino.
Now it's work very nice. And I don't know "why?" . Any idea?

There is no "5v pin" on an SD card!!!

@ChrisStratton There is a 5v pin on my sdcard module

Then the problem would be with some circuutry on the module which you have failed to.mention

If there is no file on the card, you must first create the "test.txt" file and put it in the main directory of your SD card. Your code doesn't create a file and I don't think you can even do that with the SD library. If you want to create a file, you are going to have to use the SDfat library. Also take out this part of your code :
    file.close();
file = SD.open("test.txt",FILE_WRITE);
You are just opening, then closing, and then reopening.

Note that the poster's code isn't far from the SD library examples, so for example "Your code doesn't create a file and I don't think you can even do that with the SD library." is probably untrue.

"If the file is opened for writing, it will be created if it doesn't already exist" — documentation for SD.open


text:
Two devices on one SDA input
I have two devices. Sensor for temperature and humidity and lcd screen. Both require SDA pin, and I have only one on my arduino.
I want my display to show current temperature but I don't know how to connect two things on one pin.
Can I somehow read from other pins maybe?
Also, what can I do if I have only 1 5V source and I have two devices that require 5V?
My arduino model is Arduino Mega 2560 R3
I have this aosong sensor (AM2301), and I have YwRobots 2 row LCD screen which I want to connect to my board along with sensor.
So... I'm not sure how to connect those two if both require SDA and I have only one.

You can have multiple I2C devices on the same bus (sharing both SDA and SCL), as long as they have different addresses. The library used to access them should know (or be told, if required) what the address for the device is.
If they are not I2C devices then they cannot both use SDA.
The Aosong device is not an I2C device, but there is no need to connect its "SDA" pin to the Arduino's "SDA" pin; any unused digital pin should work, as long as the library is told which pin to find it on and as long as the electrical requirements of the connection are met.

So, why is sda label on the board if it doesn't matter what hole I stick the wire in? Does it have any advantages over other holes?

The "SDA" pin on the Arduino is paired with the "SCL" pin in order to connect I2C devices.

That humidity and temperature sensor uses a one-wire serial protocol. SDA stands for Serial Data. So in essence they are kind of right, naming it SDA. But it does indeed create confusion.