Running in loop or once according to a slide switch position I have a question.

I made a system which includes a servo, a stepper and a wiper motor :)
All these parts has one job to do and I can code it. But, I want to make 2 modes in this system Single Operation, Loop operation.

for example position 1-single operation, 2-loop operation.
I can code the loop operation thanks to arduino syntax :)

But I cannot code single one. I can read switch state detection.  I want to do exactly same things, but only one time when slide switch on the position.

The code is really long and it includes Turkish defines. If you need to see the code, let me know.

Let's assume the switch is on pin 9, that the pinMode() has already been set, and that the switch reads HIGH for loop operation.

#define MODE_SWITCH  9
#define DO_LOOP  HIGH

// This loop will execute once if the mode-switch is off, or
// will execute continously if the mode-switch is on:
do {
  servo_things();
  stepper_things();
  motor_things();
} while( digitalRead(MODE_SWITCH) == DO_LOOP );

in C/C++, 'do-while' loops always execute at least once, since the condition isn't tested until after the first pass through the loop. If the 'while' condition is satisfied (or TRUE), the loop will execute again, otherwise the loop will exit.


Can I program the Arduino without having an actual board with the able to emulate a COM connection to the computer? I have ordered my Arduino, but it is not going to arrive until 2 months, and I would like to be able to emulate a COM connection to the emulated Arduino. I am writing a program that listens on the com port, and would like to test it.

The program needs to run on Windows, and emulate a COM connection, and a breadboard with a LED, and motors on it.

You could use the Simulator in Atmel Studio or something like Virtual Breadboard which looks good

The Atmel Studio simulator might take a bit of work to simulate your devices but if you have 2 months then maybe that's okay :) If you want to use the simulator in Atmel Studio then you might also find the Arduino plugin for Atmel Studio useful.

I think there are quite a few other solutions if you search google.


How to toggle LED and motor on button press? we want to have a LED turn on with the press of a button, and become brigther and brighter as times go by (whithin  a defined time frame), and when it reaches maximum brightness to turn off for a couple of seconds and then start again. in addition to that, we are trying to add a motor that will start spinning 720 degrees when the button has been pressed.
Our main problem is the fact that when we let go of the button the led turns off. How do we set the button so that when it is pressed once it turns everything on, and the led runs in a loop, but the motor doesn't; and when we press it again the whole led turns off completely and the motor runs 720 degrees in the opposite spinning direction than the previous.

Here is what we have managed so far (we didn't get to introduce the motor yet as we got stuck along the way):

const int switchPin = 11;
const int motorPin = 6;
int led = 9;
int switchState = LOW;
int previous = LOW;
int i = 0;
int fadeAmount = 5;

void setup()
{
  pinMode(led, OUTPUT);
  pinMode(motorPin, OUTPUT);
  pinMode(switchPin, INPUT);
}

void loop()
{
  int switchState = digitalRead(switchPin);

  for (int i = 0; i <= 255; i++)
  {
    analogWrite(led, i);
  }

  if (switchState == HIGH && previous == LOW)
  {
    if (i == 0)
    {
      digitalWrite (led, HIGH);
      i = i + fadeAmount;
      delay(1000);
    }

    analogWrite(led, i);

    for (int i = 255; i <= 255; i--)
    {
      digitalWrite (led, LOW);
      i = 0;
    }
  }
  else
  {
    //toggle off
    digitalWrite(led, LOW);
    i = 0;
  }
}

PS. WE are beginers. Thanks for the help and understanding!

Here is a program that should fade the LED as you specified. Initially the LED is off. If you press the button the LED starts fading within the time frame to its maximum. Then it switches to zero waits a couple of seconds and starts fading from new. If you press the button a second time the LED stops fading and is set to darkness. ;-) This happens emediately, but of cause, you can only see it if the LED is in the fading phase.

I used interrupts in order to have a well defined state transition I can work with.

Aquiring the button pin in the loop, would be more complex to handle. That would require a state variable and some state transition rules. And I was too lazy to work that out. If interupts can't be used for any reason, I would change the answer. (No Mum I don't want to ...)

I removed the motor pin as it makes no sense for the answer. I also think that one pin would not be enough if your motor (stepper, dc with feedback or a servo) should spin a certain amount of degrees.

I tested the program on a Arduino UNO. The button I used is of low quality so I had to debounce it.

If there is something not clear to you, please ask within a comment.

// Attache the LED to a PWM pin UNO -> 3,5,6,9,10,11
const byte ledPin       = 9;

// UNO -> only pin 2 or pin 3 are interrupt pins
// as we use pullups the button should be connected to GND
const byte interruptPin = 2;

// in milli seconds - The time the LED needs to fully light up
const int timeFrame  = 5000;

// in milli seconds
const int aCoupleOfSeconds = 2000;

const int fadeAmount =    5;

volatile boolean fadeOn = false;
volatile long debounceTime = 800;
volatile long actTime = 0;

int brightness =   0;

int stepCount = 256       / fadeAmount;
int stepDelay = timeFrame /  stepCount;

void setup()
{
  pinMode( ledPin,       OUTPUT       );
  pinMode( interruptPin, INPUT_PULLUP );

  attachInterrupt( digitalPinToInterrupt( interruptPin ), pressed, CHANGE );
}

void loop()
{
  if ( fadeOn )
  {
    delay( stepDelay );
    brightness += fadeAmount;
    if ( brightness >= 255 )
    {
       brightness = 0;
       analogWrite( ledPin, brightness );
       delay( aCoupleOfSeconds );
    }
    analogWrite( ledPin, brightness );
  }
  else
  {
    brightness = 0;
    analogWrite( ledPin, brightness );
  }
}

void pressed()
{
  // the debouncing does not work perfectly

  if ( digitalRead( interruptPin ) == LOW )
  {
    if ( millis() - actTime > debounceTime )
    {
      fadeOn = !fadeOn;
    }
  }
  else
  {
    actTime = millis();
  }
}


Problem programming Mini Pro via Arduino as ISP I just picked up a pair of Arduino Mini Pro 5v clone boards (Inland, sold at Microcenter, currently $4 USD) and I wanted to use my Uno as an ISP like I've done with ATmega328 and ATtiny85 chips before.  I've programmed the Uno with the instructions at the ArduinoISP tutorial page and I've connected up the Uno to the Mini Pro using the instructions at this page.  I cannot get the Arduino IDE or avrdude from the command line to successfully program these boards no matter what I try.  Except that I can use the Arduino IDE to burn a new bootloader to the Mini Pro.

I've connected up the status LEDs as well (pins 7, 8 and 9), and I can see that the programmer has an error condition (pin 8) when I attempt to program anything besides the bootloader.

Here is my avrdude command line where I tried to set the fuses on the Mini Pro:

avrdude -P /dev/tty.usbmodema0121 -b 57600 -c avrisp -p atmega328p -U lfuse:w:0xff:m -U hfuse:w:0xdb:m -U efuse:w:0xfd:m

I get the following back from avrdude:

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x1c
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1c

avrdude done.  Thank you.

I've not had any problems with using pretty much this exact same setup, but with a ATmega328 or ATtiny85 chip on a breadboard with avrdude in the past, so I'm at a loss as to what is happening here.

I've also taken a look at the ArduinoISP code, and I'm not really sure what the resp=0x1c is.  I don't see a 0x1c value defined in the STK Definitions section of the code, so I'm not sure what might be causing this.

Any pointers here would be appreciated. And yes, I do know that I can use the Uno board with the ATmega328 chip pulled to use as a programmer as well.  But I want to be able to overwrite the bootloader area with my own code like I can with a regular ATmega328 chip.

Thanks!

After poking around for a bit more, it turns out my problem was the baud rate.  I could make it work by setting it to 19200, just a little slower.  Alternatively, you can modify the ArduinoISP sketch to enable higher baud rates.  I used this post to enable 115200 baud and I was able to successfully use avrdude at the higher rates.

Not sure how I missed this before, but it's an easy to solve at least.


Arduino MKR 1010 WiFi as BLE central/client I'm trying to use my new Arduino MKR 1010 WiFi as a Bluetooth Low Energy central/client, however I could only find information on how to use it as a peripheral/server (for example with the ArduinoBLE library, which only supports peripheral mode).

Is this possible? Maybe with a different library or firmware for the integrated NINA-W102 chip?

In case this thread turns up in a search, the ArduinoBLE library now includes central and peripheral support.


How to set Alarms on the DS3231 easily so the Nano doesn't have to go to sleep with delay statements? I want my solar array sun tracker to shut down at night then move full east in the morning to catch the first rays.

I know the DS3231 can set alarms but it is not clear from its documentation how to do it with the normal library.

Delay statements are the way I have it periodically check for when to take readings, but I really want it to be able to respond to radio-remote control commands, which don't work during delays.

Q:  Is there an easier way?

Here it is:

https://github.com/sleemanj/DS3231_Simple

Example:  https://github.com/sleemanj/DS3231_Simple/blob/master/examples/z2_Alarms/Alarm/Alarm.ino

This is what I was looking for.

My system needs to be able to respond to radio remote commands while asleep, and the long delay() statements were preventing that.

These alarms solve the problem.


Generating two 1MHz, 33% duty cycle PWM signals I have been trying to generate two identical PWM signals. Both the signals should have a duty cycle of 33%. The first signal starting at 0us and the other at 0.5us. After watching the tutorials I came up with the following code but the code does not compile.

#include <PWM.h>

pinMode(3, OUTPUT);
pinMode(11, OUTPUT);
TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
TCCR2B = _BV(CS22);
OCR2A = 76;
OCR2B = 76;

The way I figured is

Duty cycle A & B= (76+1)/256= 33%. I'd appreciate any help that I can get. Cheers!

#include <PWM.h>

This is a library meant to abstract the details of the timers, so you
don't have to directly access the hardware registers. If you do access
the hardware directly, you have no use of this library: just remove this
line.

  pinMode(3, OUTPUT);

This is a program instruction (technically called a “statement”). You
cannot have instructions at the top level of the program: they must all
be within a function. Since you want all that follows to be executed
only once when the program starts (as this is just a one-time
configuration), you have to put it in setup(), as:

void setup() {
    pinMode(3, OUTPUT);
    pinMode(11, OUTPUT);
    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);
    OCR2A = 76;
    OCR2B = 76;
}

Note that a valid Arduino program also needs a loop() function, with
all the stuff that has to be executed repeatedly. In your case, there is
nothing to be executed repeatedly, but you still have to define an empty
loop() function:

void loop() {
}


How to serial connect arduino galileo to alarm system i'm a little new in this.
I have an alarm system panel which has TX,RX wires with 12V output/input.

how can i  read the output with arduino and control it with serial communication?

First of all, you'll need to make sure this is UART and not another protocol. Don't worry, if it's not UART the worst thing that could happen is jumbled data.

After that, you will need a 12v to 5v (or 3.3v) logic level shifter. When you have that you'll need to connect the Arduino to the system through the level shifter to pins 0/1.

You won't know what you'll receive or can send without looking at the serial output and doing a little tinkering. You don't even know what the serial port does. It could just be for setting up the system.


DS1820 bad reading from 4th sensor I am very new to Arduino. I want to add about 50 sensors to Arduino R3. I get good readings from 3 sensors, but when I connect 4th one, I get 'No devices found'.

Here is a diagram:

and here is the code I use:

#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
#define TEMPERATURE_PRECISION 8
#define BAUD_RATE 9600

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress devices[10];
int devicesFound = 0;

void setup(void)
{
  // start serial port
  Serial.begin(BAUD_RATE);

  sensors.begin();

  devicesFound = sensors.getDeviceCount();

  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(devicesFound, DEC);
  Serial.println(" devices.");

  // report parasite power requirements
  Serial.print("Parasite power is: ");
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  for (int i = 0; i < devicesFound; i++)
    if (!sensors.getAddress(devices[i], i))
      Serial.println("Unable to find address for Device" + i);

  // show the addresses we found on the bus
  for (int i = 0; i < devicesFound; i++)
  {
    Serial.print("Device " + (String)i + " Address: ");
    printAddress(devices[i]);
    Serial.println();
  }

  for (int i = 0; i < devicesFound; i++)
    sensors.setResolution(devices[i], TEMPERATURE_PRECISION);
}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

// function to print the temperature for a device
void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC < 10)
    Serial.print("0");

  Serial.print(tempC);
}

// function to print a device's resolution
void printResolution(DeviceAddress deviceAddress)
{
  Serial.print("Resolution: ");
  Serial.print(sensors.getResolution(deviceAddress));
  Serial.println();
}

// main function to print information about a device
void printData(DeviceAddress deviceAddress)
{
  Serial.print("Device Address: ");
  printAddress(deviceAddress);
  Serial.print(" ");
  printTemperature(deviceAddress);
  Serial.println();
}

void loop(void)
{
  if (devicesFound == 0)
  {
     Serial.println("No devices found.");
     return;
  }

  int start=millis();
  sensors.requestTemperatures();

  // print the device information
  for (int i = 0; i < devicesFound; i++)
  {
    printTemperature(devices[i]);
    if (i != devicesFound - 1)
      Serial.print(" ");
  }

  Serial.println();

  Serial.print(millis() - start);
  Serial.println(" ms passed.");
}

The resistor I use is 4.7 kΩ. What should I change to get good readings? And is it a problem to get reading from about 50 sensors?

UPDATE

So after a few trials, I managed to get readings for 18 sensors. I managed to have a mixed topology. What I did is I added close to sensors I didn't get reading a resistor (mainly 4.7k, but also few 100, 1k). At the moment I get occasionally -127 reading from some sensors, but I think I will fix that with CRC check in the program. Thanks for your help! –

Max current

For 4 sensors I wouldn't expect problem, however, for 50 it will.
The VCC/GND pin has a maximum of 200 mA, see Arduino Pin Current Limitations.

(Update after remark of Gerben, thanks!):
However, these are for the ATMega, not the Arduino R3. See Arduino Voltage and Current. It's not an official document, but made by Gabriel Staples). It contains a lot of references. But the VCC can handle 0.5 or 1A depending on USB or battery power.

This means:
The DS1820 uses 4 mA (checking a random datasheet), so 50 * 4 = 200 mA, which is way within 500 mA/1000 mA).

Non one wire sensors (not your case)

Since you have one wire sensors the following is not applicable (just leave it here for others):

None one-wire sensors use their own GPIO pin mostly. Since the Arduino doesn't have 50 GPIO pins, especially not for analog input, you need to have external IC(s), ADCs (Analog Digital Converters) or analog multiplexers, see also connecting more than 6 analog input pins to Arduino.

One wire sensors (your case)

You might find how many ds18b20 temperature sensors can I connect to one bus interesting.


What is the most Inputs on An analog Pin with a specified Accuracy on the Resistors Used? I am asking about the technique were switches and resistors in series are used on the analog pin, so it creates a voltage divider when one of the switches is pressed, it a well known technique it is described here with 5 buttons on one analog pin

http://www.instructables.com/id/How-to-access-5-buttons-through-1-Arduino-input/

Obviously we assume the circuit is set up correctly e.g. the voltage reference is stable-but such things aren't the main point of this question.
My question is about an obvious generalisation of that circuit for more inputs - and where the resistors are all replaced by, a single type of resistor, a fixed resistance value (e.g. 4k ohm) with a known error on the resistance (e.g. 5%). We use the 4k resistors to make up larger values 4k,8k,12k,16k,20k Ohms and make the 100k Ohm resistor out of twenty five 4k ohm resistors.
My question using only 4k ohm resistors (connected in series in the voltage divider) within a 5% error of their value -what is the most switches  we can theoretically connect for reliable working on one analog pin?-I'll have a guess at 20 switches.

The second question is given X ohm resistors (connected in series in the voltage divider) within a E% error of their value -what is the most switches, M,  we can theoretically connect for reliable working on one analog pin? So there will be a formula for this-so what is it?

My question using only 4k ohm resistors (connected in series in the
  voltage divider)

The circuit you are describing (a collection of identical resistors
connected in series) is quite different from the one discussed in the
link you provide. I assume you have in mind something analogous to a
digital pot, i.e. a chain of N resistors between GND and Vcc, with N
switches connecting the Arduino analog input to N taps along the chain:
N−1 taps in between consecutive resistors and one extra tap at GND¹.

simulate this circuit – Schematic created using CircuitLab

The push buttons could actually be the multiple contacts of a rotary
switch. If using real push buttons, it would be tricky to know whether a
button is being pushed or if you are just reading noise, though it can
be known by toggling the pin between output and input and using its
stray capacitance.

In this case, the worst case error happens when all the resistors on one
side of the tap are 5% too high, while all those at the other side are
5% too low. It can be easily shown that the minimum possible voltage at
tap k is

V−(k) = k(1−e)/(k(1−e) + (N−k)(1+e))×Vcc

where e = 0.05 is the 5% tolerance of the resistors. The
maximum possible voltage, V+(k), is given by the same formula
after replacing e by −e.

The graph below shows the expected voltage at each tap for a chain of
20 resistors, with the error bars showing the possible voltage
ranges. The blue curves are the analytical expressions of
V−(k) and V+(k).

As can be seen on the graph, the largest error bars are the ones closer
to the central tap. Thus, the buttons can be discriminated accurately if
the two taps closest to the center have non overlapping error bars. This
criterion could be translated into an exact formula, but the formula
would be quite complex and depend on the parity of N. I propose to do
instead some approximations, starting with a first order Taylor
expansion on the error. This expansion gives the length of the error
bars as

V+(k) − V−(k) ≈ 4/N2 k (N−k) e × Vcc

This error is maximal when k = N/2 (we will forget the parity issue):

V+(N/2) − V−(N/2k) ≈ e × Vcc

Then we say that the taps can be discriminated if this error is smaller
than the expected voltage difference between consecutive taps, namely
Vcc/N. Then the criterion is now simply

N ≤ 1/e

which is exactly what your intuition told you.

¹ The extra tap could be at Vcc rather than GND. It would be unwise,
however, to tap both GND and Vcc, as a user pressing both buttons
simultaneously would then short the power supply.

Edit to answer the questions in comments.

Yes, you could use the expressions of V+ and V− to
set the thresholds for discriminating the buttons. For example, you
could set the threshold between k and k+1 halfway between
V+(k) and V−(k+1), i.e.

threshold(k, k+1) = (V+(k) + V−(k+1)) / 2

However, if you try to compute that, you will see that it is extremely
close the average between the expected voltages. Then, you could use
that average as your threshold, which is given by a very simple formula:

threshold(k, k+1) = (k+½)/N×Vcc

Then, the pin number is just the integer closest to Vin/Vcc×N.
Assuming N = 20, this can be written as:

const float VCC = 5.0
float voltage = analogRead(PIN) * VCC / 1024;
int button_number = round(voltage / VCC * 20);

This can be optimized to use only integer arithmetics:

int button_number = (analogRead(PIN) * 5 + 128) >> 8;

Note that 20 buttons is kind of borderline. Your system could fail
if the errors due to resistor inaccuracies and those intrinsic to the
ADC (offset, gain error...) add up the wrong way. If you are building
only one device, then the safest fix would be to take note of the value
analogRead() returns for each button, and set the thresholds halfway
between consecutive values.

You could also measure the resistances of all your resistors, and
arrange them in a way that minimizes the errors. For example, if you
number the resistors from 0 to 19 in order of increasing resistance, I
would build the chain by arranging them in the following order:

0 19 2 17 4 15 6 13 8 11 9 10 7 12 5 14 3 16 1 18

Then you could most likely use the simple formula above to get the
button number at a minimal computing cost.


can i configure 2 (XBee series 2) modules using one explorer Can I configure 2 XBEE modules one then another using 1 XBEE Explorer, or I MUST do this configuration operation for them at the same time and I need 2 Explorer modules?

You only need one.
In order to communicate in Point To Point, you must configure each xbee to belong to the same NetworkID (PAN ID). XBees can only communicate with each other if they have the same network ID. Configure one, switch the xbee then configure the other (see here)

There are more advanced configurations that you can use (check this tutorial for extended information).


Receiving message from arduino through wifi I am new to arduino . I went through the basics . I want to receive message from arduino uno r3 in my laptop(ubuntu) . I have esp8266 wifi module . Arduino and esp8266 connection done . How do I proceed further ?

Download the ESP8266 extension for the Arduino board in Arduino IDE,desktop. Then select the example code for ESP8266, use the Server example. If you wanna access your board outside your home then you need to open a port in your router.


Atmega328p programming with Arduino libraries I'm trying to use the serial communication to work between a naked AVR Atmega328p and a computer (OS X and Linux Ubuntu).

I can program the atmega (using a pololu programmer), I make it blink a LED on a breadboard, it works fine.

I am using the Arduino libraries to facilitate the task. And they seem to work fine (using delay, digitalRead, digitalWrite, etc).

I use a USB-to-TTL CH340 chip bought on internet. The CH340 works fine, it is recognised both on Ubuntu and OS X, and the loopback test works (Put a jumper between the TX and RX line, launch screen, type something and it comes back in the terminal), so I assume the CH340 is properly recognise and works.

Then, I plug the CH340 on my board. The 5V on the + column of the breadboard, the GND to the - column. The circuit works, my LED blinks as requested. The loop function looks like this:

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

void loop() {
  digitalWrite(9, HIGH);   // sets the LED on
  delay(30);                     // waits for a second
  digitalWrite(9, LOW);    // sets the LED off
  delay(70);                     // waits for a second
  Serial.println("loop end");
}

As you can see, at the send of the loop I send a string on the serial line. Now, I see the blue LED blinking on the USB-to-TTL converter, so it is definitely receiving data. But when I try to connect like so:

screen /dev/cu.wchusbserialfd110 9600

on OS X, or

screen /dev/ttyUSB0 9600

on Ubuntu, nothing is displayed. I just get a black terminal.

Is the Arduino Serial works with Atmega328 ? I suppose so, as it is the same microcontroller than on the Arduino. Any idea of what I am doing wrong?

Update:

More details to answer Christ Stratton question:

My low fuse is 62: 01100010. So, according to the specifications, the internal clock is used and set at 1MHz.

I programmed the Atmega using my own test bed, a Pololu programmer (as described in the book Practical AVR Microcontrollers: Games, Gadgets, and Home Automation with the Microcontroller Used in Arduino) and avrdude (through the use of platformio).
This is the command line used by platformio to flash the ROM:

/Users/[user]/.platformio/packages/tool-avrdude/avrdude -v -p atmega328p -C /Users/[user]/.platformio/packages/tool-avrdude/avrdude.conf -c avrispv2 -B 10 -e -b 115200 -P "/dev/cu.usbmodem00149121" -U flash:w:.pioenvs/pololu/firmware.hex

According to avrdude documentation, -B 10 means bitclock is set to 10us (microseconds) so a clock at speed 100Khz.

Now if I set this -B option to 1 (1Mhz), I can't program the Atmega anymore. Avrdude just timeout:

avrdude stk500v2_ReceiveMessage(): timeout

The clock rate of your board must match the clock rate defined in the board file you used to compile your sketch.  If it does not, the baud rate will differ by the same factor.

If the actual baud rate so achieved is a valid one, you can temporarily achieve communication by setting the computer to that baud rate, but all delays and other clock-rate related functions will be off.

You should use or create a board file entry that matches your board, or use a standard clock source / clock divier setting for which there already is an entry.


Motor shield and wireless transceiver compete for same pins I would like to use these 2 components with an Arduino Uno:

Arduino Motor Shield R3
nRF24L01 2.4GHz Wireless Transceiver

I use Stepper for the motor shield, and SPI + RF24 for the wireless transceiver.

I could write 2 sketches that work perfectly, but how can I combine them together?

My issue is that they both require access to pins 11, 12 and 13.

Any help is greatly appreciated!

This is the core of embedded design and "hacking" and highlights one of my peeves about Arduino design: too much focus on the pin numbers and physical location on the PCBs, rather than the actual functions on those pins.

So? Physically move the pins on the Motor Shield. Here are 3 options in order of the most hack-ish to most-clean:

1) Use an edge cutter to cut the bottom of the pins off the motor shield then solder jumpers to the nub to other pins that are free.

2) Use a hot air station to desolder that header row, solder in your jumpers, and put back only the pins you want. Board designs with such limited foresight (like your situation) is what led me to buy my hot air station. And now I pretty much use sensor shields for my interfacing outside the stack or proto shields to be intermediate layers to translate pins.

3) Cut the trace on the motor shield PCB itself to free the SPI pins. Then find pins that have your function (pwm?) and also are NOT used by any other shields in your "stack". Solder a jumper from the exposed trace on SPI pins to your free "new" pins.

If you stalk through my answers there are write-ups on two test benches I made and you can get ideas from the various work-arounds I have employed to get my hardware working.


How to access parse cloud functions using arduino? I have created rest service using .js file on Parse.com.
I want to access cloud function from arduino.

i tried this

client.get(https://myAppID:javascript-key=myJavaScriptKey@api.parse.com/1/functions/hello");

i am getting error "Method not allowed".

Solution :
Somehow i got the answer which is as follows.I hope it will help others.

 ParseCloudFunction cloudFunction;
 cloudFunction.setFunctionName(function_name);  //string ("hello")
 cloudFunction.add("light_sensor", light); //pass parameter to cloud

 ParseResponse response = cloudFunction.send();
 Serial.println(response.getJSONBody());

I read api of Parse and there i got the class to call cloud function from
Arduino.I hope it will help others.

 ParseCloudFunction cloudFunction;
 cloudFunction.setFunctionName(fnname); //String ("hello")
 cloudFunction.add("light_sensor", 139); //parameter

 ParseResponse response = cloudFunction.send();
 Serial.println(response.getJSONBody());


Is it possible to use Wi-Fi as a wireless connection to my Arduino/Windows PC LAN without using the internet My Situation and Problem:

I am wanting to put together a system to help monitor the soil moisture content in my garden and a small heated greenhouse I use in the winter. Also, In the near future I would like to build a system to remotely monitor the nutrients in my soil and other grow media, and have it accessible through my computer using a system similar to the one I'll have monitoring the moisture levels. In both situations I am growing nearly all crops hydroponically.

I have found several instances of people doing this by having the information posted to a service provider's website. Then it is possible to access the information by way of email or connecting in some manner to the service provider's site.

I plan to store the data in the cloud, but where I live we get internet access through satellite dish or land based re-transmission sites. So, I am planning to keep all gathered data in "The Cloud" manually, once received when I turn on my computer. I even have to use a booster device in my house to get dependable cell phone service. My land line telephone service provider doesn't offer high speed internet service, so I don't presently use a smart phone. I recently read a news article talking about a similar, though more widespread situation in Australia. In Australia they call it the tyranny of distance.

In addition to my garden and greenhouse, I have several other ideas for using Arduino to gather data using wifi and do any number of other things, and most of these ideas include accessing the gathered data through my computer connected to an Arduino device as required. It would certainly be helpful if anyone would be willing to share any ideas or point me toward inexpensive solutions.

Thanks for your kind consideration.

I have a hydroponic setup working. Actually I'm working in a second version. My solution is this:

I'm using a nodeMCU, because it have WiFi and lots of memory. In the breadboard I also have a real time clock (RTC), a LDR to measure real light level, and a temp/humidity sensor (DH-11), plus a small OLED display. The green led represent the HID light for testing purposes. I still need to add more elements, but it's good enough to show you my setup.

The nodeMCU send information to a MQTT broker . I can watch that information using an MQTT client in my Android smartphone. With the same client I can send orders to the nodeMCU (like changing light schedule, etc.)

MQTT is a protocol designed for Internet of Thing. It small and simple. You need a broker (server) to receive and send messages. I'm using Mosquitto running on Linux, on a old laptop that is on all time.

This is the big picture (no Internet involved):

Mosquitto is free, and it's available for PC, Mac and Linux here.

You have free clients for Android, iPhone, Windows, Mac, and Chrome. I'm using MQTT Dash.

MQTT is lightweight, easy, multiplatform, multiclient, and the best part of it: minimal programming.


Controlling LEDs with bit bang method I'm doing a research for RGB LED chips that MCU can control with one pin. I found this LED chip and it seems controlling LEDs is not as I've tought. I understand hardware part, software side is a problem.
In chip's datasheet, on page 6, you can find chapter four Data Transfer Format.
My questions are: Why D2 has only second 24 bit, third 24 bit while D3 has only third 24 bit and why D4 has no bits? What should I do when I'm done with "updating LEDs"?
I thought controlling LEDs can be done like this:

Lets say I have five LEDs to control. Every LED has Red, Green and Blue and every color is 8-bit. Five times three is 15 bytes array.
First three bytes in array are for last LED chip. While sending the data, highest bit(bit 7) will go first.
After first three bytes, MCU will stop for X microseconds. After delay, new three bytes will push old three bytes to second LED chip.
After MCU is done with sending data, it will leave data pin low.

Thanks!

You need to send the 5x24 bits out without a pause. If you then keep the line low for over 80us, that is interpreted by all LED drivers as the reset signal. It is not stated explicitly in the datasheet (at least I haven't found it), but I guess the reset signal means, that at that time all drivers will output the received values on the LEDs. That way you can light up all LEDs at the same time with their respective data.
The picture, that you refer to, explains the automatic data cascading. The first row is what you actually send from your microcontroller and also what is seen by the first LED driver in the row. That driver will then consume the first 24 bits, that it sees. After that, it will forward the rest of the data to the next LED driver. That will now consume the first 24 bits that it sees (thus the second 24 bits, that you have send). The third LED driver will do the same. But since in that example you only send data for 3 LEDs, no data is forwarded. Then the reset pulse happens and at some point in time you send a new set of data.
So each row represents, what the corresponding LED driver will see of the data, that you send. D1 sees all the data. Each following LED driver will see 24 bits less. D4 will see nothing, since you send only 3x24 bits in that example.


Difference between SoftwareSerial and Serial From the sample code

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

What is the difference between, why use 2 types of calls to make AT command calls.

  SoftwareSerial mySerial (10,11)
  mySerial.begin(10,11)

and

  Serial.begin(9600)

Edit, this answers my question in my own words based on @jfpoilpret response.

It is important to initialize both Serial and SoftwareSerial, since SoftwareSerial is used to send the actual commands to the GSM, and Serial is used to view all the commands and their responses on the debug port of the GSM
The pins on the GSM and Arduino are used to connect the the 2, and pass on actual commands. While the RS232 is only used for debugging. We can however connect a RS232 to USB connector so as to connect the GSM to the desktop(or laptop)
The code in the loop is essential to help convert all actual commands to the debugging RS232 port, and the other way around, so as to enable us to use a tool like cutecom (on ubuntu) to pass commands to the GSM serial input pins.

  Important Note : When using cutecom ensure that you select CR line end to send commands.

All Atmel MCU, on which Arduino models are based, include special hardware for serial communication; this part of the MCU is called USART (stands for Universal Synchronous/Asynchronous Receiver/Transmitter).

Based on the Arduino model you have, you may have only one (eg on UNO) or more USART (leonardo, mega...) on the board MCU.

Each MCU USART is mapped to specific pins of the board, you cannot change those pins.

On Arduino, if you use the monitor to send debug information to your PC, then one USART is used, this is when you used Serial.

If you need more than one serial communication link (e.g. because you have some devices that communicate through serial) but your Arduino model has only one USART, then you have to use the library SoftwareSerial that "simulates" the job of an USART only by software. Hence it is much less optimized than the hardware USART.

One advantage of SoftwareSerial is that you can map it to any pair of pins you like.

Going to your code sample:

if (mySerial.available())
    Serial.write(mySerial.read());
if (Serial.available())
    mySerial.write(Serial.read());

Obviously here, Serial is used for debugging (sending info to the serial monitor of your PC), whereas mySerial is used to communciate with the GSM device.

So this sketch is used to allow you to type AT commands on the monitor, which will then be forwarded to the GSM device; conversely, any strings returned from the GSM device will be echoed to the serial monitor.


interrupt pin of attiny85 unstable I'm trying to learn how to program a MC, so maybe I didn't know much about a MC. I tried to test interrupt pin of ATtiny85 with this simple code

#include <avr/io.h>
#include <avr/interrupt.h>

void setup()
{
  GIMSK = 0b00100000;
  PCMSK = 0b00000001;
  sei();
  DDRB = 0b00010000;
}

void loop()
{
  PORTB = 0b00010000;
  _delay_ms(500);
  PORTB = 0b00000000;
  _delay_ms(500);
}

ISR(PCINT0_vect)
{
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);
  PORTB = 0b00010000;
  _delay_ms(100);
  PORTB = 0b00000000;
  _delay_ms(100);

}

This is just a blink code with an interrupt to make the LED blink faster 10 times. My question is why sometimes the LED blink faster many times with the interrupt pin is not connected to anything (open)? Didn't it have internal pull up or should I use external pull up in my circuit?

Thank you

The internal pullup is only activated, if you activate it in your code. To so, you have to write a 1 to the corresponding bit in the PORTB register, while the DDRB register is set for the pin to be an input.

So you the interrupt gets triggered randomly, because the pin was floating.

Since you are currently always write to the whole PORTB, you have to change the last bit to 1 on every PORTB write. Or you can write a 1 to it in setup() and only change the one output bit in PORTB by using

PORTB ^= 0b00010000;

This will toggle only your output pin.


One workspace, two IDEs - Possible? How can I create a workspace & projects so that either the Arduino IDE or the EclipseArduino IDE may be used to develop the project, interchangeably?

I have both IDEs installed and working but in separate workspaces.

I need:

One workspace that either IDE can understand and work in;
Either to IDE build with the physically same set of library sources;
Whichever IDE I open to see my sources as I last left them, regardless of which IDE I last used.

I want:

The source files to have conventional names - .C or .C++, not .pde or .ino;
Either IDE to build with the physically same set of library object modules;

My use-case is that I work in/with Eclipse, and I teach Arduino skills to people starting out with the Arduino IDE. I'd like to be able to prepare class work at home with Eclipse but open and project it in class with the Arduino IDE. It would be nice if I could demonstrate the two IDEs using the same code. Clearly, I could hack up a demonstration, but I'd rather do it honestly and without sync issues like having to apply twice any changes we made in class.

Update 20 Apr '16:
At @Jantje's suggestion (in the comments below his answer), I created a github issue, "Importing an ArduinoIDE project with the New Sketch Wizard and using same sketch-name, failed." The new sketch would over-write the .ino file with a new, empty sketch.

That issue got fixed in the April 14, 2016 nightly and now works as his answer to this question says it does.

Are you willing / able to work with Xcode? There is a package called embedXcode that enables Arduino development on Macs – I'm just getting up to speed with it, but it does appear to allow you to work either in Xcode or with the Arduino IDE (the .ino file is present and is what you edit in Xcode). In my testing so far it appears that the easiest thing to do is to create a project using Xcode and then you can point the Arduino IDE at the project pretty easily, getting Xcode to pick up a sketch started in the Arduino IDE is currently beyond me.

From the point of view of your students I would think that you'd want to keep the .ino file rather than make them learn about the conventions of C or C++. It would also save you the hassle of somehow managing file names – although you could probably get make to do this for you.

I haven't looked into it at all, but I think you could do something similar with Atom (a quick Google found a blog post called Arduino Development in Atom Editor and an Atom package called nino that is described as a "Toolbelt for Arduino") or Emacs, or for that matter Vim is also like to have some Arduino support.


Arduino power consumption issues I'm working on an Arduino project involving an UNO.
I'm powering a 20x4 LCD screen and I am using all the ports on the Arduino, to the last.

All but four of them are pulled high at any given time, so by the time I'm done with pulling them all up the screen is going dim when powering via USB.
So I tried powering via an external 9V 600mA adapter, but that makes the Arduino overheat and eventually shut down.
I then tried another, 12V 500mA adapter, and that one doesn't even get my UNO to the end of the setup function, and it reboots repeatedly.

Anyone got good advice? Ideas?

The official arduino uno schematic uses a NPC1117 voltage regulator. This is a linear one. This means that if you put 12V on it, and if your system requises 0.5A, you Will leak 0.5A on the 12V, and, if there is 5V on the output, 12V on the input, there is a 7V drop on the regulator, 7V * 0.5A = 3.5W that turns into heat.

To avoid overheating, the solution isn't to increase the input voltage, but to decrease it. If you have a 6.2V power supply, this will minimize overheating. At least 6.2V are required for the NPC1117 to provide a stable 5V.

An other option is to use a USB 5V power supply with an output current greater than 0.5A. This is often used with smartphones. This allows to bypass the NPC1117, but the power supply shall be exactly 5V (where exactly stands for less than 10% of over or undervoltage).

Also, please note:

  Arduino does not recommend bypass[ing the] Vin supply to directly supply 5V rail on the board as it will damage the NPC1117. See the first two line on page # 3 from the document link below. http://media.digikey.com/pdf/Data%20Sheets/Arduino%20PDFs/ArduinoEthernet.pdf
  You can either do the soldering and remove NPC1117 chip before you apply 5V directly onto the board or find a higher current capability power supply with the output voltage between 7v-12V.


int not declared in this scope This posting contains 2 sketches. the analogmux1 compiles successfully. Concerning analogmuvvolts sketch an error stating updateMux1 was not declared in this scope results. The int Mux1_State [8] = 0: is defined exactly the same in both however the error results.

I'm learning Arduino programming so there are other errors in the sketch. What I'm trying to accomplish is to display the actual voltage of each channel, not numbers which appear in the analogMux.

It would be appreciated if the community could provide me with some guidance.

Analogmux:

int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};

void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  //pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
  updateMux1();
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
    }
  }
}

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

And  analogmuxvolts

int pin_Out_S0 = 8;
int pin_Out_S1 = 9;
int pin_Out_S2 = 10;
int pin_In_Mux1 = A0;
int Mux1_State[8] = {0};
//float Mux1_State[i] =0;
int RawValue=0;
float Voltage = 0;
void setup() {
  pinMode(pin_Out_S0, OUTPUT);
  pinMode(pin_Out_S1, OUTPUT);
  pinMode(pin_Out_S2, OUTPUT);
  pinMode(pin_In_Mux1, INPUT);
  Serial.begin(9600);
}

void loop() {
 RawValue = analogRead(pin_In_Mux1);
 Voltage = (RawValue * 5.0) / 1024; //scale the ADC
  updateMux1();
  Serial.println(Mux1_State);
  for(int i = 0; i < 8; i ++) {
    if(i == 7) {
      Serial.println(Mux1_State[i]);
    } else {
      Serial.print(Mux1_State[i]);
      Serial.print(",");
      //vout = (value * 5.0) / 1024.0;
    }
  }
  Serial.print("Raw  Value = " );
  Serial.print(RawValue);
}

Declare the updateMux() function by copying it from your first sketch into your second sketch:

void updateMux1 () {
  for (int i = 0; i < 8; i++){
    digitalWrite(pin_Out_S0, HIGH && (i & B00000001));
    digitalWrite(pin_Out_S1, HIGH && (i & B00000010));
    digitalWrite(pin_Out_S2, HIGH && (i & B00000100));
    Mux1_State[i] = analogRead(pin_In_Mux1);
  }
}

And do the conversions on the stored Mux1_State[] values during printing like:

  for(int i = 0; i < 8; i ++) {
    Serial.println(Mux1_State[i]*5.0/1024.0);
    if(i == 7) {
       Serial.println();
    } else {
       Serial.print(",");
    }
  }


Using attachInterrupt() to make a reset button for my code? I have used attachInterrupt() to reset my program to the beginning. It actually interrupts while running the 3 states as shown below inside of the if statement but when I press the actual button it does not exit, it goes to the function and continuing to the next state. It only works (means exiting/resetting) after all three states have executed completely.

if(buttoncount<2){
  originalstate();
  alertstate();
  evacuationstate();

I would like to make a button to stop the program while running in the middle and start again.

Code:

// Declaring pins

// Input pins
const int sensor1button_pin = 6;
const int sensor2button_pin = 3;
const int sensor3button_pin = 4;
const int sensor4button_pin = 5;
const int sensor5button_pin = 2;
const int sensor6button_pin = 15;
const int sensor7button_pin = 15;

// Output pins
const int led1_pin = 8;
const int led2_pin = 9;
const int led3_pin = 10;
const int led4_pin = 11;
const int buzzerpin = 15;

// Initialy buzzer at false mode
boolean flag1;
boolean flag2;
int flag3 ;

// for leds
int ledState1 = LOW;   // Original
int ledState2 = LOW;   // Alert
int ledState3 = LOW;   // Evacuate
int ledState4 = LOW;   // Isolate

// Buttons
int button1_state = LOW;
int button2_state = LOW;
int button3_state = LOW;
int button4_state = LOW;
int button6_state = LOW;
int button7_state = LOW;
int button5_state = LOW;

// Other variables
int buttoncount = 0;
int reset_switch=0;

void setup() {
  // INPUT pins
  pinMode(sensor1button_pin, INPUT);
  pinMode(sensor2button_pin, INPUT);
  pinMode(sensor3button_pin, INPUT);
  pinMode(sensor4button_pin, INPUT);

  pinMode(sensor5button_pin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(sensor5button_pin), clearreset, CHANGE);

  pinMode(sensor6button_pin, INPUT);
  pinMode(sensor7button_pin, INPUT);

  // OUTPUT pins
  pinMode(buzzerpin, OUTPUT);
  pinMode(led1_pin, OUTPUT);
  pinMode(led2_pin, OUTPUT);
  pinMode(led3_pin, OUTPUT);
  pinMode(led4_pin, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  button1_state = digitalRead (sensor1button_pin);
  button2_state = digitalRead (sensor2button_pin);
  button3_state = digitalRead (sensor3button_pin);
  button4_state = digitalRead (sensor4button_pin);
  button5_state = digitalRead (sensor5button_pin);
  button6_state = digitalRead (sensor6button_pin);
  button7_state = digitalRead (sensor7button_pin);

  Serial.println(digitalRead (sensor5button_pin));

  if( button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
    delay(280);
    buttoncount = buttoncount + 1;
  }

  if (button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
    if(buttoncount<2){
      originalstate();
      alertstate();
      evacuationstate();
    }
  }
}

// LED lighting arrangements
void originalstate() {
  digitalWrite(led1_pin, HIGH);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void alertstate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, HIGH);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void evacuationstate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, HIGH);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void isolatestate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, HIGH);
}

// Clear or reset back to the begin

void clearreset() {
 button1_state = LOW;
 button2_state = LOW;
 button3_state = LOW;
 button4_state = LOW;
 button5_state = LOW;
 button6_state = LOW;
 button7_state = LOW;

 digitalWrite(led1_pin, LOW);
 digitalWrite(led2_pin, LOW);
 digitalWrite(led3_pin, LOW);

 buttoncount = 0;
 exit;
}

You should enable verbose compilation in the IDE. You will then have a
chance to see this compiler warning:

warning: statement is a reference, not call, to function ‘exit’
  exit;
      ^
warning: statement has no effect

Naming a function without calling it is a way to get a pointer to the
function. It's equivalent to &exit. But since you do nothing with that
pointer, the statement has no effect, and that's exactly what the
compiler is warning you about.

You presumably want to call the exit() function, like in:

exit(0);

Edit: That being said, exit() is probably not what you want.
This function just stops your program by putting it in an infinite loop.
If you want it to restart from scratch, you can first declare

extern "C" void __init();

then, instead of exit(0); call __init();. This will send your
program to the beginning of the initialization code from the C runtime,
which is responsible of resetting the stack and initializing the memory
(.data and .bss sections). Note that this is not equivalent to a
hardware reset because:

doing this does not run the bootloader
more importantly, it doesn't reset the IO registers of the peripherals
to their default reset state.


Replace digitalWrite with a selective bitwise operation I have the following code with digitalWrite I aim to write with bitwise operation only.
No portability concerns here whatsoever. (for atmega328p here)

#define DATAOUT 11//MOSI
byte commandbits = B11000000;
for (int i = 7; i >= 3; i--) {
    digitalWrite(DATAOUT, commandbits & (1 << i));
}

I came up with something like this below which works.

#define DATAOUT 11//MOSI
byte commandbits = B11000000;
for (int i = 7; i >= 3; i--) {
    PORTB = (PORTB &(~(1<<3))) | (((commandbits &(1 << i))>>i) << 3);
}

Is this the most concise way. Is there a way to simplify it?

Personally I'd expand it out a little:

if (commandbits & (1 << i)) {
    PORTB |= (1<<3);
} else {
    PORTB &= ~(1<<3);
}

It's far more readable, and there are less shifts to mess around with. Plus the AVR has bit set and bit clear operations which that will make use of, especially since it's now using literal values. You could actually replace those values with literals:

if (commandbits & (1 << i)) {
    PORTB |= 0x08;
} else {
    PORTB &= 0xF7;
}


Communicating Arduino with Intel Galileo I'm doing a project where I have few sensors on Arduino Uno. Now I am trying to send some data to the internet where i figured using my GSM shield with the Galileo board I have is the best solution.

The problem I am facing is that software serial is not working on Galileo so I have to use the Serial1 of Galileo board (Pin 0 and Pin 1) and I am out of serial ports. I was thinking of using serial communication between Arduino and Galileo but Galileo seems to have only pin0 and pin1 as serial and they are occupied by the GSM shield.

Is there any part I am getting wrong or any suggestions?

(other than using the sensors on Galileo and getting rid of the Arduino Uno :) )

You could use SPI/I2C as interface between Arduino and Galileo.
They are better than plain serial.


Question about include statements and details in Arduino.h file from core library This is more of a C/C++ question. However the files I am asking about are a part of the Arduino library.

In /arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/Arduino.h :

#ifndef Arduino_h
#define Arduino_h

#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>

#include <avr/pgmspace.h>
#include <avr/io.h>
#include <avr/interrupt.h>

#include "binary.h"

#ifdef __cplusplus
extern "C"{
#endif

How are these blocks found at compile time in the main sketch?

#include <avr/pgmspace.h>
#include <avr/io.h>
#include <avr/interrupt.h>

Does #include <avr/somelibrary.h> mean that this is a standard library from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc compiler?

One last question, how can there be an Arduino.h without an Arduino.c? I searched through the project but could not find an Arduino.c. All of these are probably stupid questions, as I am in the process of learning C/C++. I am completely new to it.

Does #include <avr/somelibrary.h> mean that this is a standard library from either avr-g++ or avr-gcc? As opposed to a standard g++ or gcc compiler?

No. It simply means that the compiler should check both its built-in include paths as well as any passed via the -I command line option (or its local equivalent) for a file called "avr/somelibrary.h". That AVR GCC knows where AVR Libc is located is incidental.

  One last question, how can there be an Arduino.h without an Arduino.c?

There is no obligation to match each header file with a .c/.cc/.cpp file, or vice versa.


Make the Arduino read data from the PC I will be brief. There is as windows PC running a program. This program has live updating data on it. Without modifying the PC or adding any programs to the PC, is it possible to program an Arduino to read specific data from this program. In other words the Arduino would be connected to the PC via a USB port and it would need to actively read specific data from this program without having to modify the PC in any way, software or otherwise. I do have access to the PC and can learn almost anything I need to about the program during the development of this system, however in practice, I need the Arduino to simply be plugged into this PC and begin reading its data. Is this possible?  I am not asking for a tutorial however if you could point me in the right direction that would be great.
Thanks

As the comments already stated: No, not possible. For multiple reasons:

USB is a master/slave protocol. The slave (here the Arduino) cannot do anything without the master. It can just expose it's data endpoints and hold data ready to read at these endpoints for the master or wait for data from the master on these endpoints. When the application on the PC is not programmed to speak over USB, you cannot get the data over USB.

Even directly on the PC you cannot simply extract data from a different program. That would be a very huge security risk. Even more, when just initiated via an USB device. There are USB devices, which use certain behaviors of some OS's (like auto execution of specific types) to install a virus on the PC. But even then you cannot "just read" the data. It would be way more elaborate and not possible with a simple Arduino, thus off topic here. (And you might frown upon hacking your own PC this way)

From our point of view (means leaving the hacking off limits), I would aggree with Majenko in the comments. Using the visual output is the most viable and easy solution, though your results might vary.
For that you would need a camera pointing at the screen (check if you get a good image. It might be distorted due to slow refreshing...) and use a Raspberry Pi or similar to connect it. On the Pi you can then take pictures of the screen and use an OCR tool, which will read the text from the image. Then you need to extract and structure the relevant information. (Maybe it will be easier to create subimages in your program and let the OCR tool run over these to distiguish between the different data parts). Results will hardly depend on the quality of the image. If you can live with an additional program running the PC, you could instead make the images of the screen as screenshots, which will be way better quality. Though at that point you can also put the rest of the logic on the PC and just remove the Pi.
This way will still be hard to do for a beginner, but possible.


Is it possible to use Arduino UNO programmer for other AVR microcontrollers? I got an Arduino UNO which I started using with microc for avr to add more customizations.
I'm wondering if it is possible to use the Arduino UNO programmer to program other AVR microcontrollers (I know that it is possible using ATmega 328p and 168).

The AVR microcontrollers that support ISP are all tinyAVRs other than the 4/5/9/10/20/40, and all megaAVRs.

The ATtiny4/5/9/10/20/40 requires TPI (Tiny Programming Interface). AVR XMEGA devices require the use of PDI (Program and Debug Interface). Neither can be programmed using ArduinoISP.


What are the Ramps pins on my Arduino mega? I've been working on a 3D printer and I've come to the last step, which is wiring it all up.

The 3D printer I'm making works ONLY with the Arduino Mega. No Ramps. If I need to get Ramps later, I will, but for now, can someone please help me understand which of the Ramps pin goes with which Arduino pin. For example, in the Repetier firmware, the code is like this:

#define X_STEP_PIN         54
#define X_DIR_PIN          55
#define X_ENABLE_PIN       38
#define X_MIN_PIN           3
#define X_MAX_PIN           2

But Arduino doesn't have a 54 and a 55 pin. I've been googling this and I found that Ramps pins 54 - 69  are the same as pins A0 - A15 on the Arduino Mega.

I know this but not for the other pins...

Can someone please tell me the connection of all the Ramps pins to the Arduino pins?

Like: pin 54 on Ramps = A0 on Arduino. I need this for all of the pins.

You are right, your have all the information in your question.

Pin 54 Refers to the Arduino PIN Number, nothing to do with RAMPS.
0-53 are the digital pins and the 54 is A0, etc.
So the pin numbers should go higher than 69, which is A15.


Stepper motor not working as expected Kunal Gupta:
Guys plss help me .... I am having issues in using stepper motor
I have tried both 28bjy with uln2003 and l293d .. giving it output supply of 5V .
Motor is vibrating but its shaft is not moving.
And even if shaft runs then it is different from what is expected by the logic of code
Similarly tried NEMA 17 stepper motor 4.5 KG using drv8825 driver and L293D driver ... Giving 12 v external supply.
And same results as 28bjy .... motor vibrating but its shaft is mot moving as expected or absolutely not moving
I have read and understood all the concept of driving stepper motor by full step method and hafl step method ....and using at first direct examples from net .. but still not figuring out what is the problem

Try  lowering the rpm in the code. I had a similar issue with anything over about 18rpm using certain libraries with certain stepper motors.


Transfer byte-buffer with ENC28J60 How do I transfer a series of byte[256]-buffers to a server with an ENC28J60 Ethernet adapter? I get blocks of uint8_t from an Arducam camera module and I'd like to transfer them to a host. Does somebody have an idea how to solve that? I asked a previous question regarding that topic but now new issues arrived.

This is how the array is filled:

uint8_t temp = 0, temp_last = 0;
byte buf[256];
length = myCAM.read_fifo_length();
while (length--) {
  temp_last = temp;
  temp =  SPI.transfer(0x00);
  if ((temp == 0xD9) && (temp_last == 0xFF)) {
    buf[i++] = temp;
    is_header = false;
    i = 0;
  }
  if (is_header == true) {
    //Write image data to buffer if not full
    if (i < 256)
      buf[i++] = temp;
    else {
      i = 0;
      buf[i++] = temp;
    }
  }
}

Assuming you are using the EtherCard library you can send a UDP packet with:

ether.sendUdp(packet_data, length, srcPort, hisip, dstPort );

Assuming you have already set up your source port and have the destination IP address and port in hisip and dstPort.

The prototype for the function is:

void sendUdp (char *data,uint8_t len,uint16_t sport, uint8_t *dip, uint16_t dport);

The example udpClientSendOnly.ino with the library shows you UDP sending in action.


Arduino Mega external interrupts fire randomly I'm trying to solve a nagging issue with external interrupts - this is for a slot car track lap count controller. It uses the Mega's 6 external interrupt lines connected to photo diodes. The HW itself works fine - yes, trust me, it's fantastic.

I have observed the following. The code in the loop() is surrounded with:

detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

If I omit or reduce the delay amount the random firing gets worse.

The ISR is lean and mean:

void lapDetected1() {
  lane1.lapDetected();
}

calling the method of class Lane:

    void lapDetected() { // called by ISR, short and sweet
      now = millis();
      if ((now - finish) < laneProtectionTime) {
        return;
      }
      start = finish;
      finish = now;
      count++;
      reported = false;
    }

all the variables used are declared volatile.

I don't like to use delay and I'm seeking advice on how to correctly implement ISRs and their handling.

here's the link to the entire code on GitHub: https://github.com/gabe2001/PCLapCounterWithArduino/

Thanks for any advice I can get here!
-gabe

Now, you write the following:

detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

I understand that you put this stuff into the loop, such that the loop in effect looks like this:

void loop() {
    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();
}

Assuming that the above is correct, then you will be enabling and disabling your interrupts in one long stream. You would often NOT disable your interrupts, because you don't know when the are available or not, then.

You should typically ENABLE the interrupts in the startup code, and then in the loop() you can have any Other processing you want, but not any processing referring to the interrupt processing.

The interrupt processing would take care of the button pressed etc. So - in the lane.lapdetected1() algorithm, you would take care of reading buttons pressed etc., and, you would have to attach the interrupt itself directly to your algorithm. I cannot see that you have told that when an interrupt has been happening, then the code execution goes to the ISR lane.lapdetected1() algorithm?

What you would want to do, is to setup an interrupt in the setup(), which is run once upon start of the program in the arduino, and then, providing that you want the interrupt on pin 2 (external pin), and the algorithm to run while you receive falling signals on the pin 2 is lapdetected1, then you could use the following:

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), lapdetected1, FALLING);
}

Thereby you would remove the detachAllInterrupts(), and all the way down to attachAllInterrupts() from the loop construction and thereby you would be able now to process interrupts within the lapdetected1-algorithm and run what ever you would want to run, normally, from within the loop-construction.


Trying to send .wav files between NodeMCU Im trying yo send wav files between two nodeMCU. My setup is like this
uSD Card Module -> Arduino Mega -> Node MCU

So this is my setup, where I have 4 devices like this. One will serve as the central network(where I called it "server") where it will create an access point for the 3 other devices("modules") to connect to. The server will send data by using UDP so it can broadcast to the three modules simultaneously.
I'm able to send .txt files which is stored on the uSD module. Pass the .txt file contents to the nodeMCU through serial port, then recieve it on the other NodeMCU which will then send the data to the Arduino Mega also through serial port and will store it on its uSD Shield.

When I would try .wav files. It is able to send the whole .wav file to the NodeMCU from Arduino Mega (since .wav files are too big, I divide the .wav files into sets since the serial port can't handle too large data being sent/recieved. But when it would send the data from the nodeMCU to the other nodeMCU there are parts which are not being sent. When I try to observe what are not being sent, its part of the WAV Header Format, so it needs to be sent. Ill be posting the codes Im using to send and recieve and also a screenshot/example of the wav file as it is being sent.

Server's Arduino Mega Sending data to NodeMCU Serially:

void sendFiletoSerial(char fileSend[12]){
  Serial.println();
  Serial1.println();
  if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
  Serial.print(fileSend);
  Serial.print(" Size:");
  Serial.println(myFile.fileSize());

  Serial1.print(fileSend);
  Serial1.print(" Size:");
  Serial1.println(myFile.fileSize());
  delay(1500);
  fileofSize = myFile.fileSize();
  myFile.close();
  // read from the file until there's nothing else in it:
  char data;
  long int index=0;
    for(int i =0; i<(fileofSize/tempSize);i++){
    if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
    //Serial.println(i);
    myFile.seekSet(index);
  for(int j =0; j<tempSize;j++){
  int temp = myFile.read();
 intTempFile[j]=temp;
  index++;

  }
  for(int k =0;k<tempSize;k++){
  Serial1.write(intTempFile[k]);
  }
    myFile.close();
    delay(1500);
  }
  Serial.println("LAST SET OF DATA");
    if (!myFile.open(fileSend, O_READ)) {
    sdf.errorHalt("opening test.txt for read failed");
  }
    myFile.seekSet(index);
    int lastSetSize=fileofSize-((fileofSize/tempSize)*tempSize);
    Serial.println(fileofSize-((fileofSize/tempSize)*tempSize));
  for(int j =0; j<lastSetSize;j++){
 int temp = myFile.read();

 intTempFile[j]=temp;
  index++;

  }
  Serial.println();
  Serial.println("tempFile");
  for(int k =0;k<lastSetSize;k++){
  Serial1.write(intTempFile[k]);
  }
    myFile.close();

}

Server's code for Sending from NodeMCU to other Node MCU:

    if (Serial.available()) {
          byte readStr[100];
        Serial.readBytes(readStr,100);
       // Serial.write(readStr[i]);
        }

         port.beginPacket("192.168.4.255",2390);
         for(int i =0; i <100; i++){
        port.write(readStr[i]);
         }
         port.endPacket();
      }

Module's Code for NodeMCU to recieve data from other NodeMCU:

void dumpMode(){
  while(1){
    int packetSize = port.parsePacket();
      if (packetSize) {
        port.read(packetBuffer, fileSentSize);
        Serial.write(packetBuffer);

  }
  if(Serial.available()){
    String reply = Serial.readString();
    if(reply == "STOP"){
      break;
    }

    }
  }
}

Server's NodeMCU Sent Data:

RIFFäN  WAVEfmt      À]  À]    dataÀN  €€€€€€€€€€€€€€€€€€€€€€€€

Module's NodeMCU Recieved Data:

RIFFäN€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€

Is there something im doing wrong thats why NodeMCU is not either sending or recieving every content of the wav file?

Thank you for those who will help out. :)

You could just program the NodeMCUs and skip the Megas; they have sufficient pins to drive an SD card. There's so much wrong with your code: opening and closing the same file so many times and then having to seek for every chunk because of the previous nastiness, writing and reading bytes singly instead of just passing in a buffer, among others. I also hope you know that you didn't send only the WAV data to the transmitting NodeMCU; there's a bunch of stuff (CRLF, file size, etc) before that.

Your particular problem's most likely the fact that your Mega "server" is just sending chunks continuously to the NodeMCU, never minding if the latter is reading them quickly enough that its serial buffer doesn't overflow, especially considering you're sending data over the network between chunks. You should also note that UDP isn't exactly the most reliable protocol; it's connection-less and so packets will be lost. It's generally used if packet loss isn't a big deal (in your case, it is) or if upper layers implement error control.

What you need to implement is a way for each party to confirm that they've received the next chunk before the their sender transmits the next. The Mega needs to wait for a 'go-ahead' from the NodeMCU before sending the next chunk; for instance, the NodeMCU can reply each chunk with the number of bytes it actually read, so you can know if you should reduce your chunk size to not overwhelm the NodeMCU buffer.

The packets sent over the network also need to be tagged with a sequence number (because of aforementioned error control). The NodeMCU at the receiver needs to acknowledge the packet it received each packet, perhaps by sending that packet's number to the transmitting NodeMCU. This will help ensure all packets are received and in order. Or you could just use TCP which already implements these and more.


What is using up all the RAM in my program? I am running a program on the ATtiny and for some reason I am way over the 512 bytes of RAM that are available to me. This is confusing because when I did the math by hand I should have 432 bytes. Here is my code:

#include <SoftwareSerial.h>

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(0,1);    //This uses 47 bytes of RAM

byte i = 0;      This uses 1 byte of RAM

byte pixelsArray1[128];   //Arrays use 128 bytes of RAM each
byte pixelsArray2[128];
byte pixelsArray3[128];

void setup()
{
#if FASTADC
// set prescale to 16
sbi(ADCSRA,ADPS2);
cbi(ADCSRA,ADPS1);
cbi(ADCSRA,ADPS0);
#endif

pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
pinMode(A3,INPUT);         //Input for Camera 3
pinMode(A2,INPUT);         //Input for Camera 2
pinMode(A1,INPUT);         //Input for Camera 1

mySerial.begin(9600);     //Setting the data transfer rate
}

It's telling me that I am using 510 Bytes of memory but my math gave me 432 bytes of RAM. Does anyone see what I'm missing?

There is a lot you are missing.  Such as:

SoftwareSerial is using RAM.
The system stack is using RAM.
The Arduino core software is using RAM.

There's plenty more going on than just your sketch. For instance, where do you think it stores the current millis() and micros() counts? Where do you think incoming serial data gets buffered? Where do you think your registers, PC, etc, get stashed when a function (such as setup()) is called? All that takes RAM.


Trying to understand compilation error message C:\Users\Field\Documents\Arduino\Adafruit_TCS34725-master\examples\tcs34725autorange\tcs34725autorange.ino:2:31: fatal error: Adafruit_TCS34725.h: No such file or directory

 #include "Adafruit_TCS34725.h"

                               ^

compilation terminated.

exit status 1
Error compiling.

You are trying to use a library, but it is either not installed, or is installed in the wrong location. A library, in this context, is code that supports a sensor or some other hardware or that accomplishes a task. We call them libraries because we can share and reuse them – like borrowing a book from a library.

It looks like you're trying to get the Adafruit TCS34725 color sensor going. The official source of the library is in the Adafruit's GitHub repository for the TCS34725 and there is a link at the bottom of the README for how to install a library. I'll bet that will get you back on track.


Running C for arduino Is there a compiler that I can use to run C on an arduino or any other way so that I can upload C programs to my arduino?

Perhaps you should look into here
https://github.com/arduino/Arduino/wiki/Build-Process

Arduino uses avr-gcc compiler. Basically, it is a C compiler.

There is an step by step on how to customize this process using an avr-gcc compiler of your own here
http://www.wikihow.com/Write-Arduino-Software-in-C

But I best recommend you downloading the arduino IDE on the official website to get things going. It has all the serial pairing stuff you don't really need to know to get started.

Hope it helps.


Why does Arduino IDE take so long to open? I have Arduino IDE, version 1.8.10 (Windows 10 x64, 8GB RAM, i5-7200 @2.5GHz) on a network drive mapped to D:, on a 100Mbit wired network and fast file server.

If I navigate to the network shared folder and launch 'arduino.exe', it takes at least 2 minutes for the IDE to appear.

This seems totally unreasonable considering the entire arduino.exe file is only 395kB. Seems more likely the IDE is waiting for something until a timeout occurs, before finally loading up the IDE.

What can be causing this and how can I diagnose it?

As an aside, it seems the compilation process takes longer than it should too, even for programs that use no external libraries and are very short.

The simple answer is "libraries".

Every time you start the application, all files inside your library folder are parsed.

And this is not done over your OS, but over the Java-Virtual Machine.

So it is not just slow, it is ultra-slow! Since your antivirus will probably also check each file.

Once, all files was read (maybe 1/2 of the time spent by your Arduino start), all your sketch folders are parsed.

At the end Windows devices and Arduino specific libraries are loaded.

On my Arduino IDE (is installed locally), on each starts, the Arduino IDE checks about 300.000 files. I need up to 20 seconds to load everything, before I can use the IDE.

What can you do?

Base

do not waste the library folder with unused libraries
NEVER put some documentation or non-Arduino files in your sketch folder, as they are all parsed by the IDE
disable the Antivirus for the folders:

Arduino
libraries
sketch

Advanced

If you open always the same project, you can for example edit the "preferences.txt" file.

If you remove some parameters from the preferences.txt, you will be able to lauch your IDE much faster. I created an application that statrs your Arduino IDE with personalized settings:
https://github.com/Adrianotiger/ArduinoIDE_Launcher

This application can remove some preferences like:

boardsmanager
last.* settings
recent sketches

when the Arduino starts, so it will be launched faster. But if you set the preference sketchbook.path, you can start your Arduino IDE 3-4 times faster. Just place the folder with your project libraries and you can start the IDE much faster.


How many 5.5v solar panel should i use to power arduino uno and 9v water pump? I want to create a solar powered automatic plant watering system using arduino uno, 9v water pump and soil moisture sensor.
I saw a cheap solar power online and it says  5.5v 50MA. How many of these should I buy to sufficiently supply power to my materials?
Thank you!

I actually did this exact project a few years ago. However I ran a smaller 5v water pump, light sensor, and moisture sensor, and an LCD screen. Depending how you plan on operating your plant system, I would recommend having your uno plugged into a portable charger, then having your solar panel wired to charge the power supply during the day.
If you wanna keep it basic then you should get a single, larger panel that can supply enough power to those and its less complicated than wiring 3 separate solar panels (plus higher risk of one failing) since the Arduino takes 5v to power, plus the 9v for the pump so that's 14v needed to run your watering system. If you'd like I can send you my project files and you can edit or use them how you please.


Use command line to upload program through hex file to Teensy-LC I want to make a standalone programmer for Teensy-LC in windows 8.1.

So basically I have provided the board to a client of mine and now I want to change the program loaded into the Teensy-LC board.

But the solution available right now is to send the Teensy Loader and send the hex file. But the teensy LC board is packed inside a device. So reset button cannot be pressed.

Also it would be better if this code can be burned in an installer format instead of the Teensy Loader.

Is there any way to make this work?

EDIT

My Teensy.exe does not have the option for program or reboot
The icons are not accessible

Does that mean my interrupts are disabled or there might be something else I am doing wrong?
My program loads on pressing the reset button but I cannot press the program button inside Teensy.exe

If I turn off the Auto Mode, all icons go grey.

Paul Stoffregen (Teensy creator) has released a command line version of the Teensy Loader which can be found on his website. However, this program appears to be Linux only, so unless your client has Linux, that may be a non-starter. The source code for the program is available, so you might be able to work out the logic and port it over to whatever platform you are wanting this to work on (just make sure you comply with the source code license).

All that being said, pressing the reset button is not necessary for programming. The Teensy loader should be able to trigger a reset over USB all on its own. So unless the current program on the device disables interrupts that are necessary for the USB port to function, or it was programmed with the USB port disabled (by selecting "No USB" in the USB Type menu), physically pressing the reset button isn't necessary for programming. For more details you can see this forum post.

Loading Firmware Without Pressing the Button

When programming via Arduino, it does a lot of things for you automatically. To replicate that manually, follow these steps:

Connect the Teensy to the computer via USB.
Run teensy.exe (found in C:\Program Files (x86)\Arduino\hardware\tools)
Click the button on the left to select the hex file to load.
Go ahead and leave Auto enabled (this actually doesn't matter).
Run teensy_reboot.exe (also found in C:\Program Files (x86)\Arduino\hardware\tools, this will restart the Teensy, as if you had pressed the button, and automatically start the programming process.)


Problem with STM32 and SDFat lib on other SPI port I am using STM32F103C8 and I am triing to compile a code with SDFat library. The problem is I need to use the second channel of the SPI1 (pins PB5,PB4,PB3, PA15):

I found out that is possible to use SDFat lib and include SPIClass inside its constructor. Then I could use this code:
SPIClass SPI_1(PB5,PB4,PB3, PA15);
SdFat sd(&SPI_1);

The problem is this compliation error:
no matching function for call to 'SdFat::SdFat(SPIClass*)'

Do you have any idea how to solve this error or how to work with SD card on different pins?
Here is source code of this library:
https://github.com/greiman/SdFat/blob/master/src/SdFat.h

Ok, I found out that the sdFat library is not supported on stm32 bluepill (sd card HAL peripherals are not enabled), so I decided to use basic Arduino SD library (it uses SPI commands, not HAL).
Also I have to change pins (from SPI1_1 to SPI1_2) in variant.h and PeripheralPins.c files of bluepill board. - And finally it works (SPI1_2).


Light communication from pc/app to arduino I will like to implement a serial communication protocol, using javascript in a mobile browser to make the browser background blink (alternating the color from black to white) according to the bits, to communicate a few bytes to an Arduino using some kind of light sensor (photo diode or resistor) to parse. Electric Imp did something with https://electricimp.com/platform/blinkup/ .

Is there any library or implementation or where to start guide?, if not, how would you implement it?

I fear one of the problems of using a mobile browser with javascript to light-encode the bits will be timing issues, since setTimeInterval is not perfect, I could split the screen, one half blinking continuously (clock) and the other half the data, but that will require two light sensors.

Doing bit stuffing can prevent timing problems when you are sending a lot of 0s or 1s in an row. Alternatively use Manchester encoding (slower).

On the browser side, I'd suggest using <Canvas>. Combine this with requestAnimationFrame which gives you a very accurate timestamp as an argument. Though you have to check for support as older browsers don't support that.


ATtiny84A programming without shield I am thinking about buying an ATtiny84A, which fits perfectly into my project. I want to embed it into a watch that I am designing right now. But I want to buy an SMT version so I have less space to consume. What do I need for programming it through USB? Special Atmel chip? Or just 2 digital pins from USB directly into it? Thank you very much. :)

You need to design your device to permit In Circuit Serial Programming - ISP.  This will let you continue to refine the program once the chip is in the circuit, and it will also be your primary method of programming and testing small production quantities.

Basically this means that the ISP and reset pins of your processor need to be able to be externally contacted - either by a header, pads for "pogo pin" spring contacts, an SOIC test clip, or perhaps micrograbbers hooked onto individual pins.

It also means that anything connected to those pins needs to not interfere with or be harmed by the programming process.  That particularly means that anything which could drive any of these pin needs to not do so while the MCU is being programmed, nor load them, nor get lastingly confused by operations the programmer does on them.

You'll also need an ISP programmer.  Proper ones are sold, but beware of cheap clones and marginal designs as these often give users plenty of trouble.  Fortunately, you can use an everyday Arduino running the ISP sketch to program ATtiny chips.  Do beware though, that if your target is powered at 3.3v it is not safe to use a programmer with 5v signals on it - you might get away with it a few times, but eventually it will cause issues.  So if you want to use an Arduino to ISP a lower voltage target, you either need an Arduino that runs at 3.3v, or to implement level shifting.

Do spend some effort to verify that you have the software support resources you may need for the ATtiny84A - it's one of the less common chips so it won't have the same degree of community support.

A further possibility is to use ISP to put a serial (or other) bootloader into the chip and then rely on that, however this won't cover all eventualities - if you discover you need to change the fuses, you'll need ISP for that, as it's something a bootloader can't do.


Programming an Arduino Mini 05 So, I recently bought an Arduino Mini (5V, 16MHz), and a USB to Serial Converter.
Provided are the links to both the products:
Arduino Mini,
USB to Serial Converter

Now, I tried programming the mini by connecting the pins in this order:
Rx -> tx, tx-> rx, VCC -> 5V, GND -> GND, DTR -> DTR

The computer detected the USB to Serial converter after I installed the drivers manually. However, the Arduino IDE failed to program the Arduino Mini every single time, even after I swapped the TX, RX pins.

I tried to program the Arduino Mini using an Arduino Uno (I removed the onboard Atmel Atmega microcontroller on the Uno before programming). I connected the pins in this order: TX->TX, RX->RX, 5V-> VCC, GND-> GND, RST -> DTR. From the IDE, I chose Arduino Pro Mini (5V, 16Mhz).

The Mini was programmed successfully this time.

My question: What was wrong with the USB to Serial converter? Why couldn't it program the Arduino Mini with the USB to Serial Converter?

Try to reset manually just after compiling end


Blink a LED between servo pulses Apparently using delay() commands locks the Arduino during the delay period and there are better ways to control a servo that free the Arduino to do other things at the same time as running the servo.

At this point my code consists of a servo going forwards and backwards like this:

void setup()
{
  pinMode(1, OUTPUT); // makes pin 1 an output
}
void loop()
{
for(int i = 0; i<31; ++i) { //keeps in this position for about 400ms
  digitalWrite(1, HIGH); //turns the servo pin to HIGH
  delayMicroseconds(1000); //sets the servo to move clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
  delay(19);
}

for(int i = 0; i<31; ++i) { // keeps in this position for about 400ms
  digitalWrite(1, HIGH); // turns the servo pin to HIGH
  delayMicroseconds(2000); //sets the servo to move anti-clockwise
  digitalWrite(1, LOW); //turns the servo pin to LOW
  delay(19);
}}

Where and how will I add some code that will allow the arduino to carry out another task for example blinking an led light during the approximately 20ms between servo pulses.

NOTE: The arduino is using the ATtiny 85 Processor.

Before and after the delay of 19 ms?

In setup add:

pinMode(2, OUTPUT); // LED pin output

Than changen in both cases:

  delay(19);

into

  digitalWrite(2, HIGH); // LED on
  delay(19);
  digitalWrite(2, LOW); // LED off


Is it possible to HTTP inside an ISR I am developing a 247 monitoring system with Arduino. The values need to be sent to server periodically as well as upon interrupt (Watchdog). To access the internet, I am using the SIM800 module. Now, Is it possible to HTTP inside an ISR? As far as I know, Serial communication should not be used in ISR. Then how can I communicate with SIM800? Any suggestion will be valuable.

No, you cannot do HTTP in an interrupt, and you certainly can't use SoftwareSerial in an interrupt.

To trigger a heavy task in an interrupt you just set a flag (variable) which means "this task is due to be performed". Your main loop then checks that variable, runs the task, and resets the variable ready for the next time the interrupt triggers.

In multithreading environments these flags are called semaphores (yes, from the old signalling system using flags on ships). One thread (the interrupt) signals to the other thread (loop()) that it can do something.


It is any DS2482 I2C to 1-Wire bridge functional library? Please let me know if you know any good library for DS2482 I2C to 1-Wire bridge.
I tried to use https://github.com/cybergibbons/DS2482_OneWire library  but I got errors when I'm trying to run the library examples (Read_temp_sensors and Scan_1Wire_Bus):

Error for Read_temp_sensors:
Read_temp_sensors:2:10: fatal error: DallasTemperature.h: No such file or directory

Error for Scan_1Wire_Bus:
Scan_1Wire_Bus C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp: In member function 'uint8_t OneWire::waitOnBusy()':
C:\Users\myuser\Documents\Arduino\libraries\DS2482_OneWire-master\OneWire.cpp:121:3: error: 'delayMicroseconds' was not declared in this scope
delayMicroseconds(20);
^~~~~~~~~~~~~~~~~
exit status 1 Error compiling for board Arduino Nano.

Thank you

I guess to solve the first error, you also need this library, which contains the DallasTemperature.h file. The file get's included, but is not contained in the DS2482 library. Unfortunately there is no clue for that in the readme of the library. The author didn't commit anything since 2014, so the development of the library can be considered dead from that side. Though some people have forked the library to make little changes.

And the solution to the second error is described in this issue of the DS2482 library (just adding an include of "Arduino.h" in the OneWire.cpp file).


Port Manipulation - fastest implementation I'm working on an Arduino program but am getting bogged down on what is the 'correct' implementation. I understand that multiple versions may work, so for my needs the 'correct' version will be the fastest (i.e. executing in the fewest clock cycles)

I need to set three analog input pins on my Mega 2560 - let's call them PF2-0.

I could use pinMode() - but that performs some extra checks that I want to leave out.
I could use _BV() in the process, but that's another function call I wish to avoid.

So, using port manipulation, I can write:

DDRF = 0x07; //PF2, PF1, PF0 as input
PORTF = 0x07; // Disable pullups

This should configure my three pins as inputs - and reduce any extraneous function calls. This should even be faster than writing:

DDRF = (1 << PF2) | (1 << PF1) | (1 << PF0)

Is this the fastest implementation?

*To be honest, I'm not sure how to profile this to know for sure.

The standard Arduino way of doing this is to use pinMode(). It's not
fast, but it's easy to understand, especially for beginners. And it's
portable across architectures.

If you want to go fast, then you should skip the Arduino functions and
use port manipulation, and avr-libc. The standard avr-libc way of doing
what you want is:

DDRF = _BV(PF2)   // set PF2 as output
     | _BV(PF1)   // also PF1
     | _BV(PF0);  // and PF0

This compiles to two assembly instructions: one for loading a CPU
register with the constant, and the other to copy the register to the
DDRF IO port. Notice that you set the bits for the pins you want to set
as outputs, and you clear the bits for the inputs. By default, all the
pins start as inputs.

The _BV() here is not a function call: it's a macro that expands to
(1 << (x)). The way you write the expression to the right of the =
sign is irrelevant as long as it is recognised to be a compile-time
constant. If you want to see for yourself, you can disassemble the
generated binary with the command

avr-objdump -S -C my_prog.elf > my_prog.lst

You get an assembly listing interspersed with your source. Doing this on
the example above yields:

    DDRF = _BV(PF2)   // set PF2 as output
         | _BV(PF1)   // also PF1
         | _BV(PF0);  // and PF0
100:    87 e0           ldi r24, 0x07   ; 7
102:    80 bb           out 0x10, r24   ; 16

Here, the ldi instruction means “load immediate”, i.e. load a register
(r24) with a constant value (0x07). The “out” instruction copies that
register into port 0x10 (namely DDRF). Both are single cycle
instructions, so the whole sequence takes two CPU cycles.


Analog inputs on ATtiny85 don't work I want to use a ATtiny85 to check the voltage of two 12 V batteries (later to control a relay). Therefore I'm using the analogRead() function. For programming I'm using an Arduino Mega 2560 board.

//                           +-\/-+
//  Ain0       (D  5)  PB5  1|    |8   VCC
//  Ain3       (D  3)  PB3  2|    |7   PB2  (D  2)  INT0  Ain1
//  Ain2       (D  4)  PB4  3|    |6   PB1  (D  1)        pwm1
//                     GND  4|    |5   PB0  (D  0)        pwm0
//                           +----+

For A1 this works perfectly fine. But for A2 or A3 I'm getting always a value of 15 V (thus the analog input gives 1023 respectively it thinks there is 5 V on the pin, which is not the case). I tried A0 as well, but it's the same.

For seeing the current value I put a serial - USB converter on RX, TX on PB3, PB4. So I guess they cannot work properly as analog inputs then. But still A0 does not work and without serial my LED is always on without having a voltage over 12 V.

At the moment I don't know what to do about it. No matter which of the analog pins I choose, I'm getting always a wrong value (except A1).

I'm not a hundred percent sure about A0. On some diagrams there is an A0 pin, on some not. But I tried to remove all the serial communication code and still having the LED 0 on high.

Thanks in advance!

void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  digitalWrite(0, LOW); // led for displaying the voltage
  digitalWrite(1, LOW); // blinking status led
  int sensorValue1 = 0;
  int sensorValue2 = 0;
  Serial.begin(9600);
}

void loop() {
  int sensorValue1 = analogRead(A1);
  int sensorValue2 = analogRead(A0);
  // <- the problem, A2, A3 do not work as well
  float voltage1 = sensorValue1 * (5 / 1023.00) * 3;
  float voltage2 = sensorValue2 * (5 / 1023.00) * 3;
  Serial.print(voltage1);
  Serial.print("--");
  Serial.print(voltage2);
  Serial.println();
  if ((voltage1 > 12) || (voltage2 > 12)) {
    digitalWrite(0, HIGH);
  } else {
    digitalWrite(0, LOW);
  }
  digitalWrite(1, HIGH);
  delay(1000);
  digitalWrite(1, LOW);
  delay(1000);
}

SOLUTION:
As suggested by Andrei Dragan the problem was the serial communication, which uses just the same pins as the analog inputs A2 and A3. When turned off, the problem disappeared.

As the serial communication is quite useful for me, right now I'm still using the serial communication but only with the pin for sending data. The pin for receiving data is turned off. It looks like this:

#include <SoftwareSerial.h>

#define RX    -1   // *** turned off
#define TX    4   // *** D4, Pin 3

SoftwareSerial Serial1  (RX, TX);

(I don't know if this is the best way, but it works for me.)

Once again, thanks for the help!

Any type of communication protocol uses pull-up resistors (not 100% sure that all of them do but still, it's a rule of thumb) so using the serial trick on the attiny enables the internal pull-up resistors on PB3 and PB4. I can bet the ADC value is near 1023 isn't it? Disabling the serial communication should in theory fix your problem.


What are these components in Arduino Mega Schematic? I was looking at Arduino Mega's reference schematic here and trying to understand how the circuit functions. However, I am unable to understand what these schematic symbols (marked in black rectangles) represent or what their function is. Can anyone please explain it to me?

The symbol indicates a pair of solder pads that can be bridged by the user using a blob of solder.

Here's something similar.

Figure 1. Source: CyberGibbons.


Cast from long to int How does arduino uno cast from long to int?

Does it truncate the bits? (Does it just delete the 16 most left bits?)

Yes, it just blindly chops off the upper 16 bits.  That means that the sign can change between the two.

For instance, 123456789 gets truncated to -13035 and -123456789 truncates to 13035.

To see that in more detail, look at the binary.  123456789 in binary is:

0000 0111 0101 1011 1100 1101 0001 0101

Truncate that at 16 bits and you get:

1100 1101 0001 0101

And of course the high (sign) bit is set, so the value is negative.