Unsure about how the code works for this Make-It Robotics kit I have been using a Make-It Robotics kit, that I picked up from a RadioShack that was closing, to learn more about Arduino, C, etc.  After building the line-following robot and downloading the correct libraries, I can get the robot to function as intended.  It uses 2 optical sensors in front of 2 driving wheels that are controlled by independent DC motors.  The optical sensors determine if the left or right side of the front of the robot is over a white or black area on the test track. The necessary motor then turns on to keep the black line roughly between the 2 sensors as the robot moves along. The default test track that came with the kit was a large black circle on a white background.

I want to make some modifications to the code (and maybe the underlying library files) to try to make the robot able to handle other types of paths with more acute angles and sharper turns, etc.  But, I don't understand some aspects of the highest level .ino source code file.

I am a little unsure of pasting such a long code block below and also don't think an image of it will help.  The version data for the file I'm using is below.  The files can be found online @ LINK

// ******************************************************************************    **
// * File Name          : linefollow
// * Author             : RadioShack Corporation
// * Version            : V1.0
// * Date               : 2014/01/16
// * Description        : Optical sensors send feedback to PCB
// *                      to make the robot follow a black line on a white background.
// ********************************************************************************

In this .ino file, I don't understand the code from line 68 onwards: from the Read Left/Right Optical Status onward...

I don't understand some of the bitwise operations there and don't really see how the sensor readings (whether it is over a white or black area on the surface) correlates to which motor activates to keep the robot on the course...

From my limited understanding of Arduino, this robot kit, and the code, it seems like the software and hardware have to interact in this way:

Robot moves forward using both motors turning the wheels in the same direction.  It approaches the black test circle at a shallow angle (i.e. almost tangent to it) to allow one sensor to go over the black line before the other one does.
Optical readings of each sensor are taken periodically.
If both sensors detect white space, robot continues to move forward.
If the right sensor detects that it has gone from white to black and then to white, it means that the robot needs to turn to the left to stay on the path.
To turn left, the left motor is un-powered and the right motor is powered until the right sensor detects black again.
Now that the robot is on course, it will keep turning in the direction of the sensor that detects a white to black to white transition.

I am not seeing how my intuitive understanding of the robot's operation matches with that of the code...

Indeed, the way the bitwise operations are written is confusing.

  if((sensor_in & 0xf00)==0)
    sensorValue1=sensor_in & 0xff;
  else if((sensor_in & 0xf00)>>8==1)
    sensorValue2=sensor_in & 0xff;
  if (sensorValue1 == 0x00)
    action1 =action1 & 0xfe;
  if (sensorValue1 == 0xFF)
    action1 = action1 | 0x01;
  if (sensorValue2 == 0x00)
    action1 = action1 | 0x02;
  if (sensorValue2 == 0xFF)
    action1 = action1 & 0xfd;

Basically you have two input values that can be in the same variable - differentiated by the 9th bit of the value.  Values between 0 and 255 relate to one sensor, between 256 and 511 to the other.  The bitwise operators split that into sensorValue1 and sensorValue2 accordingly.

Then those sensor values are compared to 0 or 255 and used to define the action to perform - that action being comprised of the lowest two bits of a byte variable, so you have three possible actions:

0 = both sensors off
1 = sensor 1 on, sensor 2 off
2 = sensor 1 off, sensor 2 on
3 = both sensors on

The comments in the program also tell you this information:

action1
         left        right
0x00    black        black
0x01    black        white
0x02    white        black
0x03    white        white

Now you have how to deal with the action value:

if(action1 != action2)
{
  if (action1 == 3 )
    line_following.go_forward(50);
  if (action1 == 1)
    line_following.line_following_turn_left(50);
  if (action1 == 2)
    line_following.line_following_turn_right(50);
  if (action1 == 0)
    line_following.go_forward(50);
}
action2=action1;

So if the action has changed, we can change what we are doing:

If action is 3, so if both sensors read as white, or if action is 0, so both sensors read black (in other words if both sensors read the same) then move forwards.
If action is 1 (so the left sensor reads black) then turn to the left.
If action is 2 (so the right sensor reads black) then turn to the right.

So basically if it doesn't know anything better, it drives forwards, otherwise it turns in the direction that it finds the black line, thus keeping it always on that line.  As it drifts off the line one sensor will sense white, so the robot will turn away from that whiteness and back on to the line.


SD.begin() causes SD card to pull 20mA in idle mode. Seem high? I'm working on a project that uses an Atmega328p as the primary controller. I am using the Arduino libraries for programming.

I currently have an SD card in the project. I've done quite a bit of studying on current consumption of SD card and it turns out they're quite power hungry during read/write operations. However, when an SD card is not being interacted with, I believe it should go into an idle mode in which the power consumption is much less.

Now I've noticed that when I start using the Arduino SD library, specifically SD.begin(), the current consumed is approximately 20mA. This is a continuous 20mA without any read/write operations being used. Simply selecting SD.begin().

So I've got a few questions:
- Does this seem high for an SD card that is essentially doing nothing?
- What exactly does SD.begin do? I assume it configures some pins but does it do anything else? If it's just set up, shouldn't it 'set up' and be done? Why the continuous high current?

You should look here and see if it helps. Basically:

Ensure that SD.begin() returns true because the card won't sleep if not properly initialized.
I don't know if it's been fixed but the SD library may still have a bug that prevents it from letting SD cards sleep. So try the SdFat library instead.
Try another SD card, from a reliable source.
Connect external pullups or use the Arduino's internal pull-ups with the MOSI, SCK and SS pins so they don't float.


Why does the ADC overflow when using an external Aref? I'm using an LM35 temperature sensor, and it outputs 190 mV (which agrees with 19°C). I'm using an external reference voltage which I measure as 417mV. (This is set by the pin "aRefCntrl"). So I should have a reading around 467, but I get 1023, i.e. the ADC overflows. When I use the internal 1.1V reference I get a correct reading. Any ideas?

This is my code (Arduino waits for a request from the PC to send the data):

#define lm35 A0
#define aRefCtrl 10

void setup() {
  pinMode(aRefCtrl, OUTPUT);
  digitalWrite(aRefCtrl, 0);
  analogReference(EXTERNAL);
  analogRead(lm35); // dummy read
  Serial.begin(9600);
}

void loop() {
  if ( Serial.available() ) {
    Serial.read(); // PC's request is a single byte
    int temperature = analogRead(lm35);
    Serial.println(temperature);
  }
}

follow-up on Ignacio's comment: would a decoupling capacitor do? (I can't test for the moment, I have to order some)

The minimum reference voltage is 1.0 V according to the atmega328 datasheet. See table 29-15. ADC Characteristics.


Arduino code cannot continute process Two days ago, my code is working fine on the arduino board. But yesterday, and today I tried so many time to upload the arduino code, which contains 1000 lines of code. It was successfully uploaded the code into arduino. But it only upload half code into arduino when I saw the serial monitor results (I use serial println(); test where the code is located. ) I am so confusing, why the code is working fine two days ago. but later, only half code being used. Please help.

Here is the memory I left when I uploaded it.

Sketch uses 48,314 bytes (19%) of program storage space. Maximum is 253,952 bytes.
Global variables use 2,603 bytes (31%) of dynamic memory, leaving 5,589 bytes for local variables. Maximum is 8,192 bytes.

Here is the code it stuck :
   Get Parameters
//
//  This function reads the information from the SD card for a given monitoring
//  site.
//

//

int getParameters(){
  String lowerLimit, upperLimit;

   char buffer[36];
  char newChar;
  int index, index1, index2, index3, line, theLength, numSensors;
  myFile.setTimeout(2000);
  line = 0;
  while (myFile.available()) {
    index = 0;
    do{
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    }
    while(newChar != 10);
    buffer[index] = 0;
    theLines[line] = buffer;
    Serial.print(theLines[line]);
    //here the result is something like this
    //theLines[0] , class 111
    //theLines[1] , 192.168.1.10
    //theLines[2] , Mac Address

    line += 1;
  }

//so it is working fine above the code. But here is the problem stuck.
//the code cannot go through the rest of the code below. Nothing happened!!!
  for (int line = 0; line < 10; line++){
    Serial.print(theLines[line]);

  }

A portion of your code is shown below.

  myFile.setTimeout(2000);
  ....
  while (myFile.available()) {
    index = 0;
    do {
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    } while(newChar != 10);
   ....
  }

Apparently your code is accepting and printing several lines of option setting text and then hangs up in the code extract shown above.

Suppose, for example, one extra character appears after the supposedly-last linefeed character.  Your while (myFile.available()) loop will run again.  It will store the extra character, then try to read another character.  If another character isn't available, newChar = myFile.read(); will return a -1 that your code will store.  That will happen repeatedly,  clobbering RAM.

To see if this is what's happening, you could change while(newChar != 10); to (eg) while(newChar != 10 && index<36);.  If the code then stops hanging up, look into where the extra character is coming from.


Low Cost Motorized Valve I'm looking for a low cost motorized water valve.  I've done a number of searches and have found nothing compelling.  Has anyone here used a motorized water valve with Arduino?  What would you recommend?

A fail-open solenoid might also work but I'd like to try my hand at a motorized valve.

The valves I found start at US$50.  I'm looking for something cheaper.  The purpose is tinkering and I'd like to make an "if water detected - then close valve" sketch.  Ir's simple, just more expensive than I expected.

You can get sprinkler valves, that use solenoids, for under $20 that fit on plastic PVC pipe and are designed for water, such as these at SprinklerWarehouse.  They typically use pipe sizes of about 1 inch.


New to arduino, help wiring relay I am new to arduino and need some help. I just baught light bars for my jeep and wiring harnesses with them, the harnesses come with buttons and I wanted to replace the button and have them controlled on my phone. The harnesses come with a relay and a fuse and a button all 12v, How would i go about using my raspberry pi or udoo x86(which has built in adruino) to basically replace the rocker switch so i can then turn things on and off without needing to have actual switches.

To drive a relay you'll need a transistor (a MOSFET is a good choice) and you'll need a diode across the relay coils to protect the transistor from the reverse current pulse when you remove power from the relay coils.

As Majenko says, if you Google "Arduino relay" you'll find lots of articles covering the topic. (And if you use a digital output line from your PI the exact same circuit will work.)

This MOSFET is a good option for switching high current loads with a 5V logic signal:

https://www.adafruit.com/product/355

The diode will need to be a power diode that can handle your voltage/current needs. You'll need to figure out how much current your light bar uses, and then I'd suggest a diode that can handle twice that much current (at 12V) for a margin of safety.


SIM900 GRPS Shield Power down over issue AT+CIICR cmd(Bring Wireless Coms) I'm trying to get the TinySine SIM900 GPRS Shield working to get data over the GPRS network, using Arduino MEGA.

I'm Able to register my SIM with this Shield and even , but as soon as I sent the command AT+CIICR to Bring up the Wireless Coms, the Shiled powers down, all LEDs are OFF except the Red one.

What is the source of the Problem?

Thanks

The SIM9000 shield requires up to 2 Amperes to operate its wireless functions. Thus it must be powered from an external 9 Volt power supply, and the supply should be able to supply at least 2 Amperes, preferably more.

The shield will thus not work if powered through the Arduino, or using a low current external supply. The current draw for initial setup is low, hence registration of the SIM might be fine. Enabling wireless pushes the current draw beyond what your supply can cope with. This is shutting your setup down.

Replace (or use) a 2 Amperes or better 9 Volt DC power supply, feed this power to the shield, not the Arduino, and attempt your code again.

Note that there are some changes required in using an Arduino Mega instead of the Uno with the TinySine GPRS shield, which are described in the help files and on some example videos on YouTube.


How do I know when the connections is ready between Arduino and QSerialPort I am trying to send data from QSerialPort to Arduino Mega 2560. The proccess always takes some time to establish the connection.

How do I know with QSerialPort is the connections is ready to send data?

I don't know how much time do I have to wait for that and it happens every time when I run the application.

The configuration of my QSerialPort instance is:

mSerialPort = new QSerialPort();
mSerialPort->setPortName("COM3");
mSerialPort->setBaudRate(QSerialPort::Baud9600);
mSerialPort->setDataBits(QSerialPort::Data8);
mSerialPort->setParity(QSerialPort::NoParity);
mSerialPort->setStopBits(QSerialPort::OneStop);
mSerialPort->setFlowControl(QSerialPort::NoFlowControl);
mSerialPort->open(QIODevice::ReadWrite);

I check the device configuration of COM port:

I also changed and play the Arduino delay but nothing changed.

I am sending to Arduino little piece of data. Example:

X100.10,Y10.23, H9999, ...others

And these data work when I am debugging the functions of my application. Everything is writting and work. So I am lost.

I hope all this information be usefull to give me an answer or at less some tips.

I am guessing that what you are seeing is not the port taking some time to open, but the Arduino resetting as soon as you open the serial port.  That means there is a short time while it's in the bootloader looking for an "I am here" signal from avrdude.  The timeout of that signal is configured in the bootloader, and is usually something like 1 second.

The simplest thing you can do is, as one of the first commands in your program, send an "I am ready to receive" signal to the computer (maybe just the word "OK" or something like that), which you then wait for before sending your data.


Rc receiver giving wrong values when controlling servo So I'm building a helicopter. That why I need a receiver (tgy 9x) to read the values from my controller. Those values get passed to my Arduino due where some calculation happen and then get sent to the servos.

Now the problem is the moment I move my servo all the value I get from my receiver immediately become gibberish.

The values I should get and get when I am not sending anything to my servos. These values are in microseconds.

Channel1 Channel2 Channel3 Channel4
1486     1484     1482     1472
1486     1484     1482     1472
1486     1484     1482     1472
1486     1484     1482     1472

What I get after moving the servo. These should be between 1000 and 2000.

Channel1 Channel2 Channel3 Channel4
1495     18660    1105     17182
1495     2337     5667     3070
8828     7674     8795     6198
10289    7674     8795     11404

The Arduino gets power from the USB (at the moment) and the servo from the ESC of my motor. All the grounds are connected. There is only one servo hooked up and all wires from the receiver are not anywhere near any power lines or servos.

So the question is why is the receiver giving me gibberish and how do I fix it.

Right now I have commented everything out except this:

RC_controller.h

#ifndef RC_controller
#define RC_controller

#include <Arduino.h>
#include "eeprom.h"

void RC_init();
void calc_input0();
void calc_input1();
void calc_input2();
void calc_input3();
void calc_input4();
void calc_input5();
#endif

RC_controller.cpp

#define RC_NUM_CHANNELS  8
uint32_t volatile rc_start[RC_NUM_CHANNELS];
uint32_t volatile rc_shared[RC_NUM_CHANNELS];
uint32_t volatile rc_raw[RC_NUM_CHANNELS];

int rc_channels_pin[8] = {2, 3, 4, 5, 6, 7, 8, 9};

void calc_input0() {
 int identifyer = 0;
   if (digitalRead(rc_channels_pin[identifyer]) == HIGH) {
     rc_start[identifyer] = micros();
   } else {
     rc_raw[identifyer] = (uint16_t)(micros() - rc_start[identifyer]);
   }
}

...

void RC_init()
{

 for (byte i = 0; i > RC_NUM_CHANNELS; i++)
   pinMode(rc_channels_pin, INPUT);

 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[0]), calc_input0, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[1]), calc_input1, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[2]), calc_input2, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[3]), calc_input3, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[4]), calc_input4, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[5]), calc_input5, CHANGE);
}

main.cpp

...
void setup()
{
Serial.begin(115200);
  Wire.begin();
#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif
for (int a = 0; a < 3; a++)
  swashplate[a].attach(10+a, 1200, 1800);
RC_init();
}

void loop()
{
if (rc_raw[0] < 2000)
  {
    swasplate[0].write(rc_raw[0]);
  }

  Serial.print(rc_raw[0]);
  Serial.print("    ");
  Serial.print(rc_raw[1]);
  Serial.print("    ");
  Serial.print(rc_raw[2]);
  Serial.print("    ");
  Serial.print(rc_raw[3]);
  Serial.print("    ");
  Serial.print(rc_raw[4]);
  Serial.print("    ");
  Serial.print(rc_raw[5]);
  Serial.print("    ");
  Serial.println();
}

I found the problem. The problem was with the interrupts when the program was running and doing calculations at that moment the Arduino would be interrupted and stop in the middle of it, and change the value it was doing calculations with. This somehow caused the Arduino to sent interference over the signal wires. Reading the signals with a reading guard fixed the problem.

void read_inputs()
{
  noInterrupts();

  byte identifyer = 0;
  rc_shared[identifyer] = rc_raw[identifyer];

  ...

  interrupts();
}


Resistance in Switch (negative vs positive logic) I tried in my Arduino the negative logic to get a digital input from a switch (with 10 KΩ resistance). If I want to use the positive logic what kind of resitance I have to use? For me seems that 10KOhm it to big and probably a smaller resistor should be used. How do we compute the value of the resistor? The schemes of Negative and Positive Logic from Valvano's notes/ebook - University of Texas gives 10 kΩ in both cases. Is it correct?

From a pure electronics viewpoint, there is no real difference between both circuits, the difference will be handled by your code running on the MCU, as a close switch will either be HIGH or LOW depending on the logic you used to wire your switch.

The resistor must be present for 2 reasons:

to avoid producing a shortcut between +5V and GND when the switch is closed, without it the shortcut would probably damage your power supply circuitry (if both pins are directly taken from Arduino, that would mean damaging Arduino supply circuits)
to make the voltage pin attached to the pin the "winner" of both voltage pins when the switch is closed, ie that pin will provide the level to Arduino input pin

The value of the resistor should  be:

high enough to limit the current between +5V and GND when the switch is closed, preventing damage and limiting overall power consumption of your circuit
not too high to allow providing a voltage level to the input pin

Using 10k means that, applying Ohm's law, when closing the switch, a 0.5mA current would flow from +5V to GND, which is generally acceptable in terms of consumption and cwill not damage your power supply.

Note that the input pin is "high impedance" which means it has no voltage level if not connected to anything, and it does not supply or sink any current (or more accurqtely a negligible current only).

Finally, it is good to know that Arduino MCU offers the INPUT_PULLUP mode for digital pins, where an internal resistor pulls up the pin input to 5V.  This enables you to directly connect your switch between the pin and GND. So you just have to code:

pinMode(XXX, INPUT_PULLUP);

instead of:

pinMode(XXX, INPUT);

For information, according to ATmega328P datasheet (the MCU of Arduino UNO), those internal pullup resistors have a value between 20k and 50k.


Find which WiFi device quiries a network? 1) What additional hardware sensors will be required for it?

2) What software components one shall develop to capture devices broadcasted network names?

Looking at WiFi library can not get what one can utilize for such task: there is sample on scanning yet no samples of capturing such scans

There are some cheap modules out there called ESP8266, they have the ability to connect to WiFi Networks. A Serial communication is used to talk to this WiFi module.

Edit: For monitoring purposes, that's beyond the capacities of ESP8266(and maybe not), so I would recommend going for a router instead of modules or shields. You may try TP-Link TL-WR703ND for this task. It has serial and it can run OpenWRT.

By using the router, you can configure it to be in Monitor Mode and therefore, you will be able to capture active probe requests (scans) sent by WiFi devices around the router.


Pinball - "All Lanes Lit" Bonus score is not behaving as expected I'm trying to build a (very basic) pinball machine with an Arduino Uno. This part of the code will detect when a ball passes 3 lanes. When a lane is passed, it will activate the lane(laneState), reward a score(+10) and light up an LED.

The Expected Result:

When all 3 lanes are LIT, assign a score of the lane passage(+10), assign a bonus score(+100) and reset all laneStates to 0 and turn all leds to LOW.
110 points are being added in total

Actual Result:

the last lane passed lights back up as active (while I set all of them to inactive)
120 points are being added in total (instead of 110?)

Any hints on why I see this behaviour are very welcome!

The sketch and board can be found here: https://circuits.io/circuits/2739062-poc-lane-passage-001/
Turn on 'Code Editor' and enable the Serial Monitor to see the scores.

More info:
I looked into using interrupts, but that is not an option here (the Uno only has 2 pins for interrupts, I need 3)

Thanks!

EDIT: added the code here too:

// Scores
int totalScore = 0;
const int lanePassageScore = 10; // 10 points for passing a lane
const int allLaneActiveBonus = 100; // 100 points for activating ALL lanes

// Digital pins to detect the state of the buttons
const int laneButtonPin[] = {2,3,4};
const int laneStateLedPin[] = {10,11,12};

// all three lanes are 'inactive' at the start of the game
int laneButtonState[] = {0,0,0};
int lastLaneButtonState[] = {0,0,0};
int laneState[] = {0,0,0};

void setup() {
  Serial.begin(9600); // for debugging
}

void loop() {
  // detect if lanes 1 to 3 were activated
  detectLaneButtonPassage(0); // Lane 1
  checkAllLanesLit();
  detectLaneButtonPassage(1); // Lane 2
  checkAllLanesLit();
  detectLaneButtonPassage(2); // Lane 3
  checkAllLanesLit();

  Serial.println(totalScore); // for debugging

  delay(5);
}

void detectLaneButtonPassage(int laneId){
  // Check state of the button
  laneButtonState[laneId] = digitalRead(laneButtonPin[laneId]);
  if(laneButtonState[laneId] != lastLaneButtonState[laneId]){
    if(laneButtonState[laneId] == HIGH){
      // The lane button change to an ON position, toggle the lane state
      if(laneState[laneId] == 0){
        // lane was not yet active, it becomes active now
        laneState[laneId] = 1;
        digitalWrite(laneStateLedPin[laneId], HIGH);
        rewardScore(lanePassageScore);
      }else{
        // lane was already active, it becomes inactive now
        laneState[laneId] = 0;
        digitalWrite(laneStateLedPin[laneId], LOW);
        rewardScore(lanePassageScore/2);
      }
    }
  }
  lastLaneButtonState[laneId] = laneButtonState[laneId];
}

void rewardScore(int score){
  totalScore += score;
}

void checkAllLanesLit(){
  // Check if ALL lanes are activated
  if(laneState[0]==1 && laneState[1]==1 && laneState[2]==1){
    // reset all buttons and states
    for(int laneId=0; laneId<=2; laneId++){
      laneButtonState[laneId] = 0;
      lastLaneButtonState[laneId] = 0;
      laneState[laneId] = 0;
      digitalWrite(laneStateLedPin[laneId], LOW); //Turn off led
    }
    rewardScore(allLaneActiveBonus);
  }
}

Looks like a timing issue.

Which ever order you hit the buttons in the last one always stays lit (and you get an extra 10 points added).

I set a breakpoint at:

rewardScore(allLaneActiveBonus);

...and just waited a sec and then continued and your code worked as expected.

So I think that you are setting all lines to LOW in checkAllLanesLit() and then only have a short delay (5mS) before looping round and checking again (at which point the button is still HIGH as you haven't taken your finger off it quickly enough) - resulting in the additional 10 points and that lane being lit again.


Motor does not move with 4 batteries I mada a  4wd car with ultrasonic sensors and servo. I use 4 AA 1.5 volt batteries for power. But the motor does not move. What is the problem?

In the future, please detail your attempts at solving the problem so far so we can help you better.

Approach the issue as methodically as possible. I don't know how familiar you are with electronics, so please excuse me if you think some of these questions are basic:

Ensure that the servo motor works first without any other motors or
sensors connected to the Arduino Sensor Shield (have you used this servo motor before?)
Ensure that your GVS wiring is in the correct order. Servos come with a 3 way socket that plug straight onto the Sensor Shield: G goes to the Brown or Black wire, V goes to the (middle) Red wire, S goes to the Orange wire. The good news is as the +5V is in the middle, things will not blow up if you put the 3-pin plug on the wrong way. The servo just will not work until you plug it in correctly.
Is the Arduino Sensor shield working correctly. Does the LED pin work? Do other signals sent from the board work?
Remember that servo motors work differently to normal DC motors. You need to use Pulse Width Modulation to set the position. If you have never done this before, you will find the Arduino Servo Motors page useful. Also, you will get some excellent understanding and code from this Adafruit page. It is for a different Arduino shield, but the principles are the same.


Is SPI a good way to connect two rfid modules on separate arduino boards? RFID access control

I have two separate rfid projects on separate arduino, the first project requires 2 minutes of contact between the tag and the reader after which it turns the LED on. the second project is a simple rfid access control, but on this access can only be granted if the conditions on the first tag were met. I am trying to use SPI for this but do not know if it would work, any suggestions on any other way of communication between two arduino boards?

Its very easy.

Set one PIN of ARDUINO as ouput pin. You will write that PIN HIGH when your conditions are matched in ARDUINO1 then SET LOW after 1 mS.
Connect that PIN of ARDUINO1 to external Interrupt PIN of ARDUINO2.
Write a CODE for ARDUINO2 such that when EXTERNAL INTERRUPT OCCURS it will set variable high indicating that Conditions is Matched in ARDUINO1.
While providing access to on ARDUNO2 check that variable status if it is HIGH grant access and SET it LOW.

This is the basic Structure you can follow using interrrupt.


Reading keyboard input I'm using Serial.read(); to read keyboard input from the serial monitor.
It only sends the characters after hitting enter or clicking the "send" button.
Is there a way to read keyboard input without having to use "enter"?

Not with the Serial Monitor built into the Arduino IDE. It is possible to use an external terminal program with buffering disabled though.


Laser tripwire and LDR I am planning to make a laser tripwire but I have an issue. Let me explain what I am trying to do:
Making a laser tripwire is actually pretty easy at its core. You just need an LDR and a laser diode. You look at the normal results of the LDR; it's usually around 60.
When the laser hits the LDR, it's usually around 600 so you write an if statement saying if LDR value is below 500, power the LED or buzzer.
But there is an issue here. The LDR module must be connected to Arduino with cables for signalling. I don't want that. Luckily, I have a Bluetooth module but I have no idea how to use it for sending signal to my Android phone. I know how to send signals though. So to simplify things:
1Can I send any kind of signal to my phone with Bluetooth (I am using an app called Arduino Bluecontroll but I can upload a different app if necessary)? If yes, how?

Can I send any kind of signal to my phone with Bluetooth?

You have an HC-06, which is a bluetooth Serial (UART) bridge. Thus the bluetooth device exposes the profile for a serial terminal. You can only transmit serial data. It doesn't work for HID input to the smatphone or audio. The Bluecontrol app seems to use serial. So that is not a problem.
To get the communication to work, you need to pair the HC-06 with your phone. The actual connection is then established by the app. It will send serial data to the HC-06, which will output it on its TX pin. Serial communication on its RX pin will be transmitted back to the app.
You need to test, for which baudrate the HC-06 is configured. For that write a test sketch, you use an extra serial interface (either another hardware interface or SoftwareSerial) for the HC-06 and send every byte, that you receive from it, to your PC, so that you can see, what the Arduino receives. Try different standard baudrates (like those, which are listed in the serial monitor), until you find the one, which gives you the correct output.
When that works, you can write your sketch to read the commands from the HC-06 serial interface and act accordingly. How exactly that works depends on the data, that the app is sending. Most likely is sends ASCII encoded text, each message terminated by a newline character \n. In that case you could read the data into a buffer byte by byte, when they arrive. When you read a newline character, you know, that you received a full message. Then you can process it and act accordingly.


Arduino is running as a server, but want to occasionally act as a client to update time My Arduino (actually an ESP32-based Adafruit HUZZAH32) is running as a wifi server. Its main job is to service GET requests from a user, and to periodically turn devices on and off based on the commands implicit in those GETs.

It needs to keep an accurate time/date - in order to turn devices on/off as directed.   My cheap real-time clock is off a couple seconds or more per day.   So I figure I'll use code such as the example at:

https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/

... in which the Arduino creates a client to get the time from an NTP server.  Once a day (e.g. checking for the RTC time to be 00:00hrs in my "loop"), I'll adjust the RTC using NTP.

Looking around, it sounds like this is ok, for the Arduino to act as a client, as long as it's not actively servicing a client (the user's GET requests).  Do I have that right ?   Need I worry that a user might be sending a GET when that happens ?

There is no problem with running multiple servers and use multiple clients with the WiFi library of the ESP32 core for Arduino as it is not a problem with most of the WiFi libraries for Arduino (some can't run servers (TinyGsm) or can run only one server (WiFiEsp(AT)).

But you don't need a WiFiClient for NTP time. First because NTP runs on UDP and second because the ESP32 SDK provides SNTP and the ESP32 core for Arduino wraps it in functions presented in the ESP32 examples library's SimpleTime example.


Is Fastled.io library suitable for SMD50500 led strip? I was looking for a ready to use library to control my SMD5050 color led strip, and I stumbled across FASTLED.IO library , but after reading trough their website I didn't find anywhere the support for SMD5050 color LED strip. Does anyone knows another "ready to use" animation library? Are FASTLED.IO suitable anyway?
Thanks

No. FastLED is for addressable LEDs (like the WS2812B). Yours aren't addressable. You just need to set the colour you want with the PWM outputs of your Arduino. Changing the PWM values is not hard and you don't need a library to do it for you.


Long freezes at the beginning of sd card transfer I am creating an accelerometer data logger that writes data to sd card. After some sort of "warm-up" everything works perfectly for at least ~15 minutes (which is what I have tested so far).

However, during the first few seconds there are some pretty long freezes of the File.write() function (180 ms instead of 50us for normal writes!) which I can identify on an oscilloscope (see picture below, signal low after starting high indicates File.write() phases) and which I can also see in the data if I include in them a milis() timestamp.

Since RAM on the Atmega328 is limited, there is also tight limits to the amount of sensor data I can buffer (I am using an interrupt for transfer from the sensor, where I can store the data to a buffer and thus bridge the shorter sd card delays).

I stripped down my code to the absolute bare bones, just writing nonsense data instead of those from the accelerometer. What could be the reason for these freezes? The data rate is the same during the whole run. Isn't the sd card electrically or logically initialized after SD.begin()? It doesn't seem to be a problem with erasing flash memory blocks because it only occurs in the beginning. Even if I restart the application a second time (after staying electrically on all the time) it already shows no freezes anymore. Whereas if I unplug/plug power, the freezes in the beginning reappear.

And most importantly: how can I solve it?

Of course I could write the dummy data before receiving the start button. But how many? Does it depend on sd card type? Does it depend on cpu or spi clock frequency? I want a robust solution that doesn't break when I use another type of sd.

Code:

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

const int chipSelect = 10; // chip select of the sd card
const int pushButton = 9; // this is where the start button is (on a pulldown resistor)
const int debugPin = 1; // a line used for displaying a debug bit on the oscilloscope

const int bufferSize = 14;
byte buffer[bufferSize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; // for the test just dummy values

String fileName = "accellog.raw";

void setup()
{
  pinMode(pushButton, INPUT);
  pinMode(debugPin, OUTPUT);

  if (!SD.begin(chipSelect))
  {
    // on error stop execution
    for(;;);
  }
}

void loop()
{
  // wait for the start button to be pressed
  while (digitalRead(pushButton) == HIGH);
  delay(100); // debounce delay
  while (digitalRead(pushButton) == LOW);

  // remove old file on sd card
  if (SD.exists(fileName)) SD.remove(fileName);

  File dataFile = SD.open(fileName, FILE_WRITE);

  if (dataFile)
  {
    // Debugging: indicate start of whole data transfer on an oscilloscope
    digitalWrite(debugPin, HIGH);

    int lastMillis = millis();

    for (long i=0; i<10000; i++)
    {
      // wait until millis changes in order to get SD writes at
      // whole millisecond boundaries (some cycles may get lost,
      // however, during lengthy SD writes)
      int tempMillis = millis();
      while (tempMillis == lastMillis)
      {
        tempMillis = millis();
      }
      lastMillis = tempMillis;

      // Debugging: indicate file access times by sending 0 to the DSO
      digitalWrite(debugPin, LOW);

      dataFile.write(buffer,bufferSize);

      // Debugging: indicate end of file access on DSO
      digitalWrite(debugPin, HIGH);
    }

    // Debugging: indicate end of whole data transfer
    digitalWrite(debugPin, LOW);

    dataFile.close();
  }
  else
  {
    // on error stop execution
    for (;;);
  }
}

As a temporary workaround I have come to the following procedure:

I inserted a function that writes a certain amount of bytes into a dummy file, closes it and finally deletes it, all during setup().

This does indeed seem to cure the freezes if (in my scenario) I write at least 6 blocks (512 bytes each, i.e. total 3072 Bytes). Remarkably there were always exactly 6 freezes visible in my oscilloscope plots. I don't even remotely know what the meaning of this magic number 6 could be...

Just to have some additional safety in case I choose a different type of sd card (and this workaround becomes permanently temporary...), I have decided to write 16 kB into the dummy file. This is ~5 times as much as the empirical minimum value (3 kB) and is still pretty fast so that I don't notice any significant startup delay after power-up.

This empiric approach is still unsatisfactory though, and certainly a piece of mediocre engineering. So I won't mark my answer as accepted, to leave the chance for someone else to give a more well-founded answer.

void writeAndEraseDummyFileToEliminateFreeze()
{
  if (SD.exists("dummy")) SD.remove("dummy");
  File dummyFile = SD.open("dummy", FILE_WRITE);
  int n = 16384/recordSize+1; // write 16kB in chunks of recordSize (just because we have that buffer already
  for (int i=0; i<n; i++)
  {
    // buffer values are uninitialized, but who cares, we'll dispose of them anyway
    dummyFile.write(buffer,recordSize);
  }
  dummyFile.close();
  SD.remove("dummy");
}

void setup()
{
  // ...other things I have been already doing...

  writeAndEraseDummyFileToEliminateFreeze();
}


Continuous servo speed control with Arduino Uno controller and servo shield It is very simple device, 2 continuous servos FS5113R, rotates continuously in one direction. Here is device original content, which is this servo shield it looks like russian, and here is library, I have added to Arduino IDE, also I have original code, which runs this device, given below.

I'm trying to figure out, what can I do with speed, to run it slower, I've tried change  delay(15); number to 1000, but it moves with same speed.  I've tried  increment variable  in  while (z < 2) loop and pass it with interval, but speed is same:

#include <Wire.h>
#include <Multiservo.h>

#define SERVO_COUNT 2

Multiservo servo[SERVO_COUNT];

int pos1 = 0;
int pos2 = 0;

int z = 1;

void setup(void)
{
  Wire.begin();

  for (int i = 0; i < SERVO_COUNT; ++i)
  {
    servo[i].attach(i);
    servo[i].write(0);
  }
}

void loop(void)
{
    while (z < 2){
        pos1 + 1;
        pos2 + 1;
        servo[1].write(pos1);
        servo[2].write(pos2);
        delay(15);
    }
}

Any advice, guide or example would be useful

The speed of your servo is controlled by the pulswidth of a square wave signal. According to the datascheet of the servo the motor stops on a pulsewith of about 1500 µSec (+- 5 µSec).

From 1500 to 900 μSec the motor turns clock wise. And it getting faster with decreasing pulsewidth.

From 1500 to 2100 μSec the motor turns counter clock wise. And it getting faster with increasing pulsewidth.

Next we have to check whether your shield and the library can handle that values and which value you have to give to the servo[i].write(?) function. I can read cyrillic but I do not understand russian good enough to read the f. manual. So I have to look into the code on GitHub (https://github.com/amperka/Multiservo/blob/master/library/Multiservo ).

Et voila:

Multiservo::attach(int pin, int minPulse, int maxPulse)

You can define the min and max pulseWidth, that's great. Let's do it:

#include <Multiservo.h>
#define SERVO_COUNT 2

Multiservo servo[SERVO_COUNT];
// speed is 0 ( full speed CW )
int speed = 0;

void setup(void)
{
  for (int i = 0; i < SERVO_COUNT; ++i)
  {
    servo[i].attach( i, 900, 2100);
    // 900 - 2100 is mapped from 0 to 180
    // so 90 is the middle where the motor stopps
    // 180 the motor runs as fast as possible CCW
    // 0 the motor runs as fast as possible CW
    servo[i].write( speed );
  }
}

void loop(void)
{
   // Here I halt the program if the motor stops.
   // If you use a lower value than 89 you can halt the program
   // at the corresponding speed. If you use a higher value instead of 89
   // the motor starts rotating counter clockwise.
   // Do not use a value greater then 179 or less than 1.
   if ( ++speed > 89 ) speed = 90;

   servo[1].write( speed );
   servo[2].write( speed );

   delay(25);
}

Ah, of cause I have not hte hardware, so I can not test the program. Use it as an example.


What's the problem with baudrate? I was trying to evaluate the speed of communication between pc and Arduino, using this code in Arduino:

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

void loop() {
  Serial.println("Ciao Arduino");
}

and this in Python:

import time, serial

arduino = serial.Serial('/dev/cu.usbmodem1421', 250000)

time.sleep(3)
count = 0
start = time.time()
while True:
   a = arduino.readline()
   print a
   count = count+1
   time1 = time.time()
   if time1-start >1 :
      print "--" + str(count)
      print a
      count = 0
      start=time1

Wich print out how many readline() he managed to do to evaluate the speed in further project.
And I realized two things:

The program is working even with different baudrate
and with correct baudrate(For ex. 300-300 or 250000-25000) the baudrate is irrelevant(and wrong), I mean the 300 baudrate makes 20000 readline() and the 250000 make 5000 of them.

What's the problem? thank you

On a direct USB CDC/ACM connection (as you get on the Micro) there is no such thing as baud rate.

Any baud rate setting performed by the host (the PC) is merely an instruction to the device (the Arduino) to say "I would like you to operate at this speed", not "I would like you to communicate with me at this speed".

It is used in situations where the PC may want to set the baud rate of a real UART interface within the device, such as when the ATMega16U2 is used as a USB interface on the Uno - in that case the PC tells the 16U2 that it wants to communicate at, say, 115200 baud, and the 16U2 sets its UART (the one that communicates with the ATMega328P) to 115200 baud. The actual PC to ATMega16U2 (or ATMega32U4 in the case of the Micro) is at the native USB 2 bulk packet rate.

It is also used as a "reset" instruction to the ATMega32U4 - if the CDC/ACM port is opened by the PC at 1200 baud and then immediately closed again the 32U4 resets and enters the bootloader. This makes programming (usually) easy, as long as the program on the chip hasn't crashed and left the USB interface in an unusable condition (as sometimes happens).


LCD screen stops displaying after DC motor starts LCD screen stops displaying after DC motor starts
I have 3 main components: LCD, thermal resistor, and a DC motor running a fan. The LCD displays the temperature reading from the thermal resistor and then after it hits a certain temperature the motor turns on.

A few seconds after the motor has been turned on the LCD will go blank (but still powered on). I tried connecting a 100uF electrolytic capacitor across between the logic supply pins on the LCD and a 0.47 µF ceramic between the motor terminals.

I did this because i'm assuming since the motor in operation (its commutator) produces voltage/ current "spikes" they can be coupled back through the common power supply. This could provide some immunity against them actually getting to the display driver and interfering with its operation.

What I did kind of helped, but I feel like I am missing something. Any suggestions?

(the link is to the picture of my circuit I quickly made online)

A brush DC electric motor and many other similar devices will produce random noise as well as uneven power demands and should be powered independently of logic circuits such as processors and LCDs.  It is very difficult to mediate noise sources and almost always better to remove them from where they are causing harm or unexpected results.

It is also important to power a project with a supply capable of providing more than the expected amperage during highest demand.  Many will calculate the highest amperage demand and select a power supply which is rated at double the amperage.

If you are using batteries, note that a 9 volt battery (which usually contains 6 cells) on average supplies about 500mAh.  Not much and likely not enough to run a motor with out momentarily dropping the voltage.  Where as a D-size battery supplies about 15000mAh.  Different battery chemistries change the mAh rating drastically.  500mAh and 15000mAh are about what one may expect from Alkaline batteries.

If using a USB power source, note that older USB ports are only obliged to supply 500mA at any given time.  If this current limit is exceeded, the voltage may drop under 5 volts.

There are many designs on the internet where the motor is powered from the Arduino.  This may be possible for smaller motors however you are having unexpected behavior.  Consider using one or more of the following suggestions to mitigate your problems:

Avoid low mAh batteries such as common 9 volt batteries.  Instead use a battery that can provide higher mAh like D Size cells.
Avoid powering noisy or current demanding devices directly from the Arduino.  Consider an independent power supply and use a common ground.
It may be possible to use a single power supply with good results if the power supply is rated at higher amperage than the peak total maximum amperage.


Wiring Lilypad USB + ESP8266 Serial WiFi Module I am trying to solve the following scenario:
Lilypad USB connected to WIFI through ESP8266 Serial WiFi Module.

http://arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardLilyPadUSB

http://www.seeedstudio.com/wiki/WiFi_Serial_Transceiver_Module

According to the wiki:
I should connect to TX RX pins. None of them are present as "selectable pins", because they are built in.

This post Using LilyPad Arduino USB with LilyPad Xbee Shield  talks about using SoftwareSerial something that is new to me.

Could anyone explain how should I proceed with the wiring and if possible a sample sketch just to connect the lilypad usb with the WIFI module to my personal WIFI.

Edit:

I found the following tutorial (spanish one but easy to follow...) where they use the Arduino UNO. I tried the example with the software serial and it worked.
I saw in that tutorial sometimes the pin RST is needed. So I tried to do the same with the lilypad USB, but still didn't work.

First, upload the sketch below to your Arduino. Then, try to tie RX (pin 3) and TX (pin 2) of SoftwareSerial together. Open the Serial Monitor and send some text and see if you get it back as a response.

#include <SoftwareSerial.h>
SoftwareSerial Serial1(3, 2);

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

void loop()
  {
     if (Serial1.available())
         { char c = Serial1.read() ;
           Serial.print(c);
         }
     if (Serial.available())
         {  char c = Serial.read();
            Serial1.print(c);
         }
   }

Once you get a response, then your SoftwareSerial part is working and you can then try to connect to your ESP8266.


How do I code delay inside a ISR? I have built a basic obstacle avoidance robot. When the sensor senses an obstacle it gives a RISING interrupt to pin 2. At this moment I want the robot to come back for 2 seconds and turn right for 2 seconds.

I have code to turn back and rotate right but I cannot use the delay() function inside the ISR so how do I code this?

An ISR should be kept as short as possible, since while it runs, no other interrupts can be handled (including the one powering the delay() function. Thus you cannot delay that easy inside an ISR and you shouldn't do it either.

Instead you should set a simple flag variable in the ISR and then check this flag inside your loop() function. If the flag is set, you can execute the corresponding code inside the main code instead of inside an ISR.

A typical flag definition is a single byte (since then every read/write action is atomic and cannot be interrupted by an ISR). Be sure to set it volatile, so that the compiler knows, that this variable may change any time.

volatile byte interrupt_flag = 0;

In the ISR you can set this variable to 1 for example and then in your main loop() function:

if(interrupt_flag){
    // Do whatever you need to do here
    interrupt_flag = 0; // reset the flag variable
}


How to on/off light dimmer using another pin? In recent project, I'm working with light dimmer.

Let me explain with example of fan. In switch board, we have a fan switch which can able to ON/OFF our fan & FAN REGULATOR which vary speed of our fan. Now, when our switch ON then our fan start and then with help of regulator we can vary speed of fan. And when we switch OFF then our fan stop and we can't do anything means not vary fan speed. Same things I want in my light dimmer. One push button pressed once then it's just start my light dimmer and vise versa operation. And When push button pressed again then it's just stop my light dimmer.

Here is my full code.

int kPinPWM = 9; // This pin provides PWM values

int kPinSW1 = 6; // PUSH BUTTON // This pin used for increase PWM values
int kPinSW2 = 7; // PUSH BUTTON // This pin used for decrease PWM values

int kPinSw = 10; // PUSH BUTTON // This pin used for ON/OFF PWM pin means ON/OFF pin 9

int i = 0;

int temp = 0; // Flag

void setup()
{
  pinMode(kPinPWM, OUTPUT);

  pinMode(kPinSW1, INPUT);
  pinMode(kPinSW2, INPUT);

  digitalWrite(kPinSW1, HIGH);
  digitalWrite(kPinSW2, HIGH);

  pinMode(kPinSw, INPUT);

  digitalWrite(kPinSw, HIGH);
}

void loop()
{
  if(digitalRead(kPinSw) == LOW && temp == 0) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 0
  {
    temp = 1; // Change value to 1 // temp = 1

    digitalWrite(kPinPWM, HIGH); // Turn ON PWM pin (PIN 9)

    if(digitalRead(kPinSW1) == LOW) // Pressed PUSH BUTTON to increase PWM value
    {
      i++;

      if(i > 4)
      {
        i = 4;
      }

      while(digitalRead(kPinSW1) == LOW); //Until PUSH BUTTON pressed
    }

    if(digitalRead(kPinSW2) == LOW) // Pressed PUSH BUTTON to decrease PWM value
    {
      i--;

      if(i < 0)
      {
        i = 0;
      }

      while(digitalRead(kPinSW2) == LOW); //Until PUSH BUTTON pressed
    }

    switch (i)
    {
      case 0:
              analogWrite(kPinPWM, 0); // When Button pressed not pressed send 0 value
      break;

      case 1:
              analogWrite(kPinPWM, 64); // When Button pressed and i = 1 send 64 value
      break;

      case 2:
              analogWrite(kPinPWM, 128); // When Button pressed and i = 2 send 128 value
      break;

      case 3:
             analogWrite(kPinPWM, 192); // When Button pressed and i = 3 send 192 value
      break;

      case 4:
             analogWrite(kPinPWM, 255); // When Button pressed and i = 4 send 255 value
      break;
    }
  }

  if(digitalRead(kPinSw) == LOW && temp == 1) //If I pressed PUSH BUTTOPN(PIN 10) and temp = 1
  {
    temp = 0; // Change value to 0 // temp = 0

    digitalWrite(kPinPWM, LOW); Turn OFF PWM pin (PIN 9)
  }
}

Finally I find out solution. Here, I detect when switch becomes pressed instead of  button is pressed. So, for that I used StateChangeDetection. So while loop just removed from code. And I made function to perform dimmer and vise versa operation.
k
So, now I'm able to ON/OFF the PWM pin. And also vary PWM pin. Thanks everyone for your effort.

Here, it's my full code.

const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;

const int pwmPin = 9;

const int onOffPin = 10;

int buttonState1 = 0;
int lastButtonState1 = 0;

int buttonState2 = 0;
int lastButtonState2 = 0;

int buttonState3 = 0;
int lastButtonState3 = 0;

int buttonPushCounter = 0;

int onOffCounter = 0;

void setup()
{
   pinMode(buttonPin1, INPUT);
   pinMode(buttonPin1, INPUT);

   pinMode(pwmPin, OUTPUT);

   pinMode(onOffPin, OUTPUT);

   Serial.begin(9600);
}

void loop()
{
   buttonState3 = digitalRead(buttonPin3);

   if(buttonState3 != lastButtonState3)
   {
     if(buttonState3 == HIGH)
     {
       onOffCounter++;
       Serial.println("Button 3 on");
       Serial.print("number of button 3 pushes:  ");
       Serial.println(onOffCounter);
     }
     else
     {
       Serial.println("Button 3 off");
     }
     delay(50);
   }

   lastButtonState3 = buttonState3;

   if(onOffCounter % 2 == 0)
   {
     Serial.println("Switch is OFF");

     analogWrite(pwmPin, 0);
   }
   else
   {
      PWM_fun();

      Serial.println("Switch is ON");
   }
}

void PWM_fun()
{
  buttonState1 = digitalRead(buttonPin1);

  if (buttonState1 != lastButtonState1)
  {
    if (buttonState1 == HIGH)
    {
      buttonPushCounter++;
      Serial.println("Button 1 on");
      Serial.print("number of button 1 pushes:  ");
      Serial.println(buttonPushCounter);

      if(buttonPushCounter > 4)
      {
         buttonPushCounter = 4;
      }
    }
    else
    {
      Serial.println("Button 1 off");
    }
    delay(50);
  }

  lastButtonState1 = buttonState1;

  buttonState2 = digitalRead(buttonPin2);

  if(buttonState2 != lastButtonState2)
  {
    if(buttonState2 == HIGH)
    {
      buttonPushCounter--;
      Serial.println("Button 2 on");
      Serial.print("number of button 2 pushes:  ");
      Serial.println(buttonPushCounter);

      if(buttonPushCounter < 0)
      {
         buttonPushCounter = 0;
      }
    }
    else
    {
      Serial.println("Button 2 off");
    }
    delay(50);
  }

  lastButtonState2 = buttonState2;

  switch (buttonPushCounter)
  {
      case 0:
              analogWrite(pwmPin, 0);
      break;

      case 1:
              analogWrite(pwmPin, 64);
      break;

      case 2:
              analogWrite(pwmPin, 128);
      break;

      case 3:
              analogWrite(pwmPin, 192);
      break;

      case 4:
              analogWrite(pwmPin, 255);
      break;
  }
}


Parsing sd card file to polymorphic objects I am trying to read a file from sd card and parse them to polymorphic objects, then have an array of pointers to them so i can access them later.

I was wondering what the best format would be to save these objects in, i was looking at https://github.com/bblanchon/ArduinoJson but i don't know if it's possible to deserialize them to the right object.

Is this even possible?

There is no such thing as serialization/deserialization in C++. You can read the data values from an object, and you can write data values to an object, as long as you either expose the properties as public, or create "getter" and "setter" member functions.

It is then up to you to store and retrieve that data in whatever form you like.

You could store the raw RAM data that corresponds to an object, however if there are any pointers in that object they will be stored as just that - a pointer - which will be meaningless when reloaded. So it's better to store the data values manually.

How you store the data depends on what the data is. Yes, you can use JSON format if you so choose - it has good abstraction for storing strings, escaping special characters, etc. So it would be quite convenient - however, it's quite a heavyweight arrangement. A lighter method would be to store binary data directly, but that is inflexible and can't easily store different types of data in different ways for different objects.

CSV format is quick and easy to parse, but you have to manually deal with things like commas in data strings, etc.


How to use a microSD card reader with SCK instead of CLK? I've bought this microSD reader/writer: http://www.ebay.com/itm/131132034753

I've found only one tutorial, where the pins are similar to my pins, but in the example there is a CLK instead of SCK: https://learn.sparkfun.com/tutorials/microsd-shield-and-sd-breakout-hookup-guide

The pins on my MicroSD reader are:

CS
SCK
MOSI
MISO
VCC
GND

SCK stands for SPI ClocK

CLK stands for SPI CLocK

Two different acronyms for the same thing.


Using AVR Timer Within an ISR I'm trying to create an ISR which operates for 15 seconds when a particular button is pressed. I'm attempting to use the AVR functions on my Arduino Uno to start counting when it enters the ISR, then quit the loop when it reaches 15 seconds.

I'm having difficulty reasoning out where the counter is actually stored that I want to use for my while loop.

Here is my code so far:

#define button_pin 2
#define duration 15
#define osc_in 0

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

const float convert = 5.0/1023.0;

void setup() {

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  attachInterrupt(digitalPinToInterrupt(button_pin), button_interrupt, CHANGE);

  sei();

  pinMode(button_pin, INPUT);
  Serial.begin(9600);
}

void loop() {
    //int channel1 = analogRead(osc_in);

//while (millis() < 10000)
  //Serial.println(millis());
  //Serial.println(channel1 * convert);
  //channel2 = channel1;
}

void button_interrupt(){
  //(# timer counts + 1) = (target time) / (timer resolution)
  //int timer_counts = duration/(pow(6.4, -5));
  //int dur = 234374;
  OCR1A = 234374;
  TCCR1B |= (1 << CS10);

  while (????????){
    int channel1 = analogRead(osc_in);
    Serial.println(channel1 * convert);
  }
}

Don't do delays inside an ISR. Don't do serial prints inside an ISR. Read this.

You need to redesign. The ISR can set a flag, that you then test in loop. Do the delay in loop.


Wemos D1 mini won't connect to WiFi: status code 6 So I have a Wemos D1 mini which I want to connect to my WiFI in order to let is push sensor data to my server. But I cannot connect it with my WiFi as I get a code 6.
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  Serial.print(WiFi.status());
}

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

The Serial.print(WiFi.status()); prints 6 which is WL_CONNECT_FAILED if I'm right.
I checked the router and it uses WPA/WPA2, the ssid and password are correct. The router is using 2.4 GHz with WiFi 802.11b and 802.11g.
I used the board to scan, with the example code provided by the esp8266 board manager library thing, and it found my SSID with the ones of my neighbors.
Can somebody tell me what is going wrong?
I already checked solutions like: This one , github answers, etc.
Edit: It can connect to a mobile phone hotspot. It gives code 6 1 time and then it connects. Any one an idea how I connect to the WiFi the router is providing ?

Apparently, something went wrong with connecting to the router. The router was casting 802.11 g + n, which for some reason, made the esp8266 give a code 6. I have tried 802.11 b, 802.11 b+g+n, 802.11 n, which work all fine.
So I updated the settings that the router now uses 802.11n and the esp8266 can now connect to the internet!


How to NOT repeat a piece of code again and again? I have a VERY long code:

  Sketch uses 30468 bytes (92%) of program storage space. Maximum is
  32768 bytes.

I've been trying to reduce it's size so i can write more code, one of my main part of code which repeated many times in switch cases or in if statements is related to de-bouncing the buttons.

Here's a piece of my code as an example:

  case 12:
    if ((millis() - millistimer) > BounceD) {
      if (receivedValue == RFb) {
        magnetDistance += 5;
        millistimer = millis();
        receivedValue = 0;
      }
    }
    if ((millis() - millistimer) > BounceD) {
      if (receivedValue == RFd) {
        magnetDistance -= 5;
        millistimer = millis();
        receivedValue = 0;
      }
    }
    break;

The de-bouncing actions happens in each and every case and for each and every button.

There's two buttons which in each case increase/decrease different values.

How to avoid repeating the de-bouncing action for every button?

EDIT:

The recievedValue is updated via RC buttons value once any button is pressed on the remote.

In the short example of above, first find out what is a duplicate (the two outer if statements including their body), than the differences:

Rfb versus Rfd
+5 versus -5

Than make a function for the duplicated code, and turn all differences into a parameter (I don't know the type of Rfd, so I take an int for it).

You will get:

case 12:
  processButton(&Rfb,  5); // Offset magnet distance by +5
  processButton(&RFd, -5); // Offset magnet distance by -5
  break;

  ...

void processButton(int* rf, int diff)
{
  if ((millis() - millistimer) > BounceD) {
    if (receivedValue == *rf) {
      magnetDistance += diff;
      millistimer = millis();
      *rf = 0;
    }
  }
}

Note that if magnetDistance and millistimer are local variables you also have to pass them (as pointer to change the value), if they are globals you can keep the code as is above.

UPDATE

The way parameter works is as follows. E.g.

processButton(Rfb,  5);

Will call the following function:

void processButton(int rf, int diff)

Where value rf will be Rfb, and diff will be 5 (+5).

Thus when magnetDistance += diff; is executed, diff will be +5 and magnetDistance will be increased with +5. In the next call, magnetDistance will be -5 and thus will be subtracted.

UPDATE 2

To change a variable, you have to pass it as pointer, otherwise the (copied) parameter value will be changed and not return its value to the called function. So you have to give the parameter as an address (& operator), and use -> instead of . to get to the value.


Passing a static array to a function I have a functon that creates a instance of KeyReport and I want to fill statically the KeyReport.keys array. I'm new in the Arduino world so I'll put a example to explain it better:

void sendKey(byte keys[6], byte modifiers)
{
  KeyReport report = {0};

  report.keys = keys; // This is my main trouble
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

void setup(){
delay(3000);
sendKey( {0x17,0,0,0,0,0}, 0x5); // I want to send hardcoded reports like this
}

void loop(){}

report.keys = keys; // This is my main trouble

You can't assign the contents of one array to the contents of another array.  You can only copy the contents manually from one to the other.

The simplest way is with a loop:

for (int i = 0; i < 6; i++) {
    report.keys[i] = keys[i];
}

There is a helper function - memcpy() - which can do it for you if you prefer:

memcpy(report.keys, keys, 6);

It effectively does exactly the same thing - copy 6 bytes starting from the address of keys into the addresses starting at report.keys.

As for the "hard coded" reports I suggest you create some const arrays in the global context - and even use PROGMEM to ensure they consume no RAM. That, of course, requires an entirely different way of passing and accessing the data.  It may be simpler to split the report into 6 individual variables and pass each byte separately:

void sendKey(byte k0, byte k1, byte k2, byte k3,
             byte k4, byte k5, byte modifiers)
{
  KeyReport report = {0};

  report.keys[0] = k0;
  report.keys[1] = k1;
  report.keys[2] = k2;
  report.keys[3] = k3;
  report.keys[4] = k4;
  report.keys[5] = k5;
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

sendKey(0x17, 0, 0, 0, 0, 0, 0x05);

Yes, it's a little more long winded in the function, but calling the function is somewhat more simplified over the other options.


Can stack size be determined by free heap? i have NodeMCU with es8266 onboard on it. I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen. So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen.

Indeed they do. And such things can be a pain to track down.

  So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

No, you can't.  The "free" amount of heap does not equate to the top address of heap. Heap can (and generally does) have holes in it. The "free" space is the sum of all those holes plus any extra "heap reserved" space above the highest heap entry.

To get the current stack usage you need to know two things:

The staring address of the stack, and
The current extent of the stack

Item 1 will be a fixed value, though what that value is I have no clue, but some reading will surely give you that value.

Item 2 can be obtained by allocating a local variable in a function and getting the address of that variable.

If all you care about is the change in stack imposed by your code you can record the "starting" stack point and use that in point 1.  For example:

char *stack_start;

void setup() {
    char stack;
    stack_start = &stack;
}

Then you can use that to get the current stack size compared to the start of your program:

uint32_t stack_size() {
    char stack;
    return (uint32_t)stack_start - (uint32_t)&stack;
}

  one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

No.  Use of String and other dynamic allocation is what causes memory fragmentation.


Motor shield leaves no pins accessible I just bought a motor shield for my UNO, in the pic below:

Plugging it into the uno leaves no pins accessible on the board. I’d like to use it to build a robot car, but there’s nowhere to plug in the ultrasonic sensors. Do I need to solder some pins to the row at the top of the pic, or to the through-board holes on the right labelled A0-5?

According to tutorial, the shield uses almost all D pins. Free are pins 2 and 13. If servo is not used the pins 9 and 10 are free too. The pin 2 has the extra hole to solder a wire or a single pin header.

All analog pins are free and the shield enables to solder headers for them with additional header rows for 5V and ground for every A pin.

You can use analog pins as digital pins to connect the ultrasonic sensor.

Connection of I2C devices is possible on A4 and A5 pins.

The shield doesn't alow to stack a next shield, because it heats up.


How to wait for next n bytes in I2C exchange? I'm trying to get data from a sensor, but don't see how I can get data back. I'm looking at the data on the I2C bus with a logic analyzer, and I'm sending what I expect, but I seem to cut off the slave before he can respond.  My understanding from the datasheet is that I need to send this command to wake it up and request a measurement:

0xD8 0x30 0x0A

and then I need to send this command to get the data:

0xD8 0x06 0xD9

#define HEARTBEAT_PIN            (13)

#define 7BIT_ADDR                (0x6C)
#define ADDR_WRITE               (0xD8)
#define ADDR_READ                (0xD9)

#define MAX_NUM_RX_BYTES         (8)
#define MAX_NUM_TX_BYTES         (8)

static uint8_t tx_buffer[MAX_NUM_TX_BYTES];
static uint8_t rx_buffer[MAX_NUM_RX_BYTES];
static uint8_t new_rx_data;

void setup(void) {
  // Clear any module memory
  memset(tx_buffer, 0, MAX_NUM_TX_BYTES);
  memset(rx_buffer, 0, MAX_NUM_RX_BYTES);
  new_rx_data = false;

  Wire.begin();
}

void loop(void) {
  RequestMeasurement();
  delay(10);
  GetData();
  delay(500);
}

void RequestMeasurement(void) {
  // MR: 0xD8 0x30 0x0A
  // Internal (to IC) register address?
  tx_buffer[0] = 0x30;
  // Request-measurement command
  tx_buffer[1] = 0x0A;
  Wire.beginTransmission(7BIT_ADDR);
  Wire.write(tx_buffer, 2);
  Wire.endTransmission(true);
}

void GetData(void) {
  // GD: 0xD8 0x06 0xD9 0x?? 0x?? 0x?? 0x?? 0x?? (0x?? => slave data)
  // Slave address + 'write' indication bit
  // Internal (to IC) register address?
  tx_buffer[0] = 0x06;
  // Slave address + 'read' indication bit
  tx_buffer[1] = ADDR_READ;

  Wire.beginTransmission(7BIT_ADDR);
  Wire.write(tx_buffer, 2);
  Wire.endTransmission(true);

  // HOW DO I LEAVE THE BUS OPEN LONG ENOUGH
  // FOR THE SLAVE DEVICE TO RESPOND WITH THE DATA?
  //Wire.requestFrom(7BIT_ADDR, 3, true);
}

First off; when talking about I2C bus, an important point to clarify: did you connect pullup resistors to both SDA and SCL lines (A4 and A5 respectively)? Without those, the I2C bus will not work properly.

Next, I2C protocol is quite low-level and a bit complex; but fortunately, the Wire library that comes with Arduino helps a lot and hides some of this complexity.

When using Wire library, there is a first point to keep in mind:

The device address is 7 bits only, the 8th bit is used to define the direction of data (read or write). You don't need to care about this direction bit as Wire deals with it for you.

In your situation, the device address is 0x6C, ie 1101100 in binary.

The commands you mentioned that you want to send to the device, 0xD8 0x30 0x0A and 0xD8 0x06 0xD9 already include the device address and the write bit (0):

0xD8 is 1101 1000 ie 1101100 plus the 0 direction bit at the end.

Please note that 0xD8 0x06 0xD9 is made of 2 commands actually:

0xD8 0x06 is a write command to tell the device hich register we want to read
0xD9 is just the device address followed by the read bit (1): this is the way the I2C master tells a slave that the former will now wait for data sent from the latter.

It is important to split this command in 2 because each will use a specific API from Wire library.

Writing to your device with the Wire library will be done this way:

// First command: start measurement
Wire.beginTransmission(0x6C);
Wire.write(0x30);
Wire.write(0x0A);
Wire.endTransmission();

// Second command: tell the device what register we want to read
Wire.beginTransmission(0x6C);
Wire.write(0x0A);
Wire.endTransmission();

Then you can start reading from your device with a different API:

Wire.requestFrom(0x6C, 3);
byte b1 = Wire.read();
byte b2 = Wire.read();
byte b3 = Wire.read();
// Now rebuild value from the 3 bytes just read...

Note that Wire.requestFrom(0x6C, 3); will send the 0xD9 that is calculated from the device address 0x6C and the read bit. SO you don't have (and you should not) send 0xD9 yourself, Wire doesit for you.

Please note that I use Wire.endTransmission() without the stop argument. Not sure if this is mandatory, but it worked fine on my I2C experiments.


Too slow start up with Atmega2560 on custom PCB I have some several custom PCB's based on Atmega 2560.
I am using AVRISP MarkII for flashing. No bootloader.

Flashing is flawless, it just works. I have one assembled PCB works as it should be, no issues.

But, the other one has a quite time lag in its functions.
It has also been flashed OK but, it is not running quite OK.

Here are my observations;

By asserting Reset, I expect four leds on the pcb running (on and then off) by 100ms intervals one after each others. This is happening in the very beginning in Setup() section of the program.

Note that: Leds are connected to MCU via mosfets. If MCU output is LOW, they are ON and vice versa.

So, with this problematic PCB, all leds come ON all together after 10 seconds after pressing reset button and they stay almost 60 seconds before they start the sequence (on and then off) as coded.

And then that sequence is also slowly occurring. It is not 100ms as I coded but almost 4 seconds or so.

I am suspecting from the external clock (16Mhz) circuitry but I can't proof it accurately as I don't have oscilloscope at hand.

You may see the simple code I use to test that behavior;

void TestLeds() {
    unsigned long interval = 100;

    digitalWrite(LED1_PIN, LOW);
    delay(interval);
    digitalWrite(LED1_PIN, HIGH);
    delay(interval);

    digitalWrite(LED2_PIN, LOW);
    delay(interval);
    digitalWrite(LED2_PIN, HIGH);
    delay(interval);

    digitalWrite(LED3_PIN, LOW);
    delay(interval);
    digitalWrite(LED3_PIN, HIGH);
    delay(interval);

    digitalWrite(LED4_PIN, LOW);
    delay(interval);
    digitalWrite(LED4_PIN, HIGH);
}

How/where should I check the bottle-neck on that?

Thank you.

EDIT:

To be more specific, I add this output regarding programming;
here

I am closing the case. It is not 100% satisfaction though. Because, using Visual Studio with Visual Micro didn't help me on that issue in a natural way but something else.

For the future reference for somebody might get benefit out of this, I like to explain here what I did to get over this issue briefly. As @Gerben (big credits go to him) has pointed the right direction, I did check fuses by installing Atmel Studio 7 and use its programmer.

Yes, the fuses were completely wrong. I have therefore read the fuses from my healthy PCB and noted aside and then applied these very same fuse settings to the slow working PCB. I have just programmed the fuses, Firmware was the one I programmed earlier in the uC. So, voilà, the slowness has gone.

I think I am going to use Atmel Studio 7 now on next to Visual Studio as it has everything built-in including Arduino support.

Thanks everybody involved.


Using Arduino for simultaneous lighting effects I am building a computer for my son (me).  I'm trying to spark his interest in computer technology, so my idea is to drive multiple case lighting effects with a microprocessor or controller.  I went with the arduino over the pi because of simplicity of the system.

There are several lighting effects I want to drive, simultaneously, and that's where I'm wondering if the arduino is well suited, because the effects need to make use of delay(), and with it being single threaded I'm struggling to figure out how to make each output operate independently.

To give you an idea of what the microcontroller needs to drive simultaneously:

Flicker pattern using random delay values for outer case lighting
Heartbeat pattern for CPU cooling block
Blacklight / UV LED lighting for coolant lines.
Strobing LEDs aimed at the fans to make them look stationary.

Trying to run all these effects in a linear loop with delay() operators just doesn't seem to be feasible.

Do I need to get an UNO for each effect?  Or is there a way of making these outputs operate independently?

Avoid delay() and use specific times of next actions and compare them to millis().  For a random time, set something like:

now=millis();
...
if(nextFlicker < now) {
   toggleFlicker();
   nextFlicker=now+random(10000);
}
if(nextPulse < now) {
   nextPulse=now+ isPulseOn? 100 : 1000 ;
   togglePulse();
}

...

If you are running more than the 50 day roll-over time of millis(), you may need some care to handle the overflows.  See http://playground.arduino.cc/Code/TimingRollover

For the strobing leds, investigate the timer-controlled outputs outputs.


Serial communication stops when I connect the tx cable I'm using the apc220 rf modules. Now I'm having the following problem:

My receiving arduino uno only receives data when the tx pin on the arduino (rx pin on the rf module) is disconnected. As soon as I connect the tx pin my serial monitor receives only the value 0.

Is my rf module broken, or can someone help me with this?

To have two serial ports on Arduino board like Uno use SoftwareSerial.h.

Example

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2,3); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  Serial.println("Hello!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

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

Now after opening Serial monitor you should see Hello! and then you can test SoftwareSerial.

DO NOT FORGET!!!

When you connect to pins 2,3 or etc, this is TTL voltage level. You can't connect direct to RS232.


Problems with serial communication from Arduino to Bluetooth HC-05 I just purchased some HC-05 Bluetooth devices and I have followed the directions to put the devices in AT command mode by holding EN HIGH when the HC-05 powers up.  When I do this the HC-05 goes into the "slow blink" to indicate it is in command mode.  However, when I send it "AT" I get odd characters in the response.

Note that when I type "AT" I get exactly 4 characters back.  They are just not the "OK" characters I expect.  I also verified that the Arduino IDE serial console is sending both NL and CR characters.

BTW, here is the Mel Patrick HC-05 authored setup program I am running:

https://raw.githubusercontent.com/dmccreary/coderdojo-robots/master/src/bluetooth-remote/hc-05-setup/hc-05-setup.ino

It has been suggested that the data from the HC-05 is only going up to 3.3v and that might be the cause of the problem, since the Arduino is looking for a 0-5 volt signal.

I also note that when I remove the TDX line from the HC-05 that no responses come back.  So I suspect that it is getting the "AT" fine through the RTX from the Arduino to the HC-05.  It is just some problem in the return data format.

Is there a simple transistor circuit I can hookup to shift the levels back to 0 to 5 volts from the 0 to 3.3 volts?

I am also using an Arduino Nano if that makes any difference.

Thanks - Dan

If you use software serial for Bluetooth, you need to set the baud rate and the default baud rate of HC-05 is 38400.

You can change this baud to the desired with AT command.


Arduino --> RPI I2C issue ok, I feel like this should be simple, but I am at a loss

Simple code mock up to send 4 bytes(mimicking a float)  over I2C from Arduino to rpi. I am trying to create a state machine so that I can request certain "registers" containing 4 bytes each. I send a byte from pi to arduino indicating what "register" I want, then read back 4 bytes.  I was attemping to reset the state back to NO_STATE after the end of the switch statement, but it effects the bytes received by the pi, and I dont see how.

#include <Wire.h>
#define SLAVE_ADDRESS 0x04

//States
#define NO_STATE 0x00
#define GET_BAT_TEMP 0x03

byte state = NO_STATE;
void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
}

void loop() {
  delay(100);
}

// callback for received data
void receiveData(int byteCount){

  while(Wire.available()) {
    state = Wire.read();
  }
  Serial.print("Got:");
  Serial.println(state);
}

// callback for sending data
void sendData(){
  Serial.println("Sending...");
  byte b[4]={1,1,1,1};

  switch (state){
    case NO_STATE:
      //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
      Wire.write(0);
      Wire.write(0);
      Wire.write(0);
      Wire.write(0);
      break;
    case GET_BAT_TEMP:
      //send battery temp
      Wire.write(3);
      Wire.write(3);
      Wire.write(3);
      Wire.write(3);
      break;
    default:
      Wire.write(9);
      Wire.write(9);
      Wire.write(9);
      Wire.write(9);
      //send back error code
  }
  //reset state to none
  state=NO_STATE;

}

with this code I receive [3,0,0,0]

if I comment out the line

//state=NO_STATE;

I then receive back [3,3,3,3]

which is what I would expect. But I do not see how reseting the state "after" all the bytes are sent would cause an issue

output from arduino shows entering that function only once, and sending the 4 bytes

Got:3
Sending...
Sending...
Sending...
Sending...

I'm not an expert, but I think I found why it is not working.

The main problem is that you are using always the same byte (0, 3 or 9) for debugging, so you are not noticing that it is not sending four bytes, but only one, and the function gets called four times. This is obvious however from the reply on the serial interface (+1 for adding it in the question, good work).

What you can do is to track how many bytes you sent, and send the successive one. After the bytes are all sent you can reset back the state. The code can be something like

//States
#define NO_STATE 0x00
#define GET_BAT_TEMP 0x03

byte sentData;
byte batteryLevel[4]={3,4,5,6};

byte state = NO_STATE;
void setup() {
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Wire.begin(SLAVE_ADDRESS);
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);
}

void loop() {
  // delay(100); // Useless, let it cycle at its max speed
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
        state = Wire.read();
        sentData = 0;
    }
    Serial.print("Got:");
    Serial.println(state);
}

// callback for sending data
void sendData(){
    Serial.println("Sending...");

    switch (state){
        case NO_STATE:
            //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
            Wire.write(0);
            break;
        case GET_BAT_TEMP:
            //send battery temp
            Wire.write(batteryLevel[sentData]);
            if (sentData < 3)
                sentData++;
            else
                //reset state to none
                state=NO_STATE;
            break;
        default:
            Wire.write(9);
            //send back error code
    }
}

I haven't tested it, so forgive any bugs. But I'm sure  you understood the main point.

Just some remarks: the delay is useless (you are not saving energy or other with it, so just remove it); the serial is ok for debugging, but I think you should remove it from the code you will use (not ok to stop the interrupts for such a long time).

And most important: I hope you considered the 5V vs 3.3V voltage problem on the I2C ;)

In any case, I second Look Alterno: good way to ask a question, with all the information needed.

EDIT: as pointed out in the comments, there exist a function to send all the data together. I'm not sure how it behaves in different conditions (e.g. when less bytes are requested), but if you trust the communication the function can be simplified in

// callback for sending data
void sendData(){
    Serial.println("Sending...");

    switch (state){
        case NO_STATE:
            //bad state   not sure if can return only byte, may need to return 4 zeros or somthing
            Wire.write(0);
            break;
        case GET_BAT_TEMP:
            //send battery temp
            Wire.write(batteryLevel, 4);
            state=NO_STATE;
            break;
        default:
            Wire.write(9);
            //send back error code
    }
}

(and the sentData variable becomes useless)


Arduino Orion Upload - Which Board When Compiling I'm trying to compile and upload the example code for the arduino robotics starter kit (https://github.com/Makeblock-official/Makeblock-Library and https://raw.githubusercontent.com/Makeblock-official/Assembly-Instructions/master/Starter_Robot_Kit_IR_Instruction.pdf).

In the IDE to compile the code, you need to select the appropiate 'board' for the sketch, and the Arduino Orion isn't listed.  Should I just compile under the Arduino Uno, which I believe the Orion is based on?

Yes, the "Orion" is just an Uno in a different shape with different connectors.  Just treat it like an ordinary Uno.

Similarly the "Baseboard" is just a Leonardo in a different shape with different connectors.


Arduino piezo-buzzer melody for car alarm I would like to play car alarm sound through Arduino buzzer - something like this https://youtu.be/nuPHwijMsIg
Does anybody have a library for such melody?

I think what you're really asking for is a library of sounds (in the form of code), rather than a code library in the normal sense.  I'd like such a thing too (specifically a retro-gaming style laser noise), but extensive googling hasn't found anything, though someone has made a sketch of the Tetris theme.
A car alarm is probably fairly easy - a couple of for loops changing the frequency of a tone(); My Arduino and piezo buzzer are at home but playing that YouTube and using a spectrum analyser app on my phone it looks like (using the waterfall display mode):

The first alarm is looping from 1000Hz to 2200Hz over about 250ms, then back down again.  - The next 2 are falling tones, from 1kHz down to about 500 over 250 or 500ms.
Then we've got a rising tone 500 Hz to 1kHz  over 2s
A beep at about 2.2kHz, 250ms on/off
A two-tone siren at 1 and 1.5kHz, 1s of each.

Times and frequencies were indeed a little off, and many of the frequency ramps aren't linear, but here's something to play with.  The more interesting alarms are in there, along with a couple of laser zaps.  The square-wave drive of a piezo (leading to interesting harmonics), and the complete lack of a low frequency response (nothing below about a few hundred Hz on the one I have here) limit things a little, but it compares well to a Lego siren I have
int beep_pin=10;
int gap=1000;

void setup() {
  // put your setup code here, to run once:
  pinMode(beep_pin, OUTPUT);
}

void zap1()
{
    for (float f=3000;f>40;f=f*0.93){
    tone(beep_pin,f);
    delay(10);
  }
}

void zap2()
{
    for (float f=3000;f>10;f=f*0.85){
    tone(beep_pin,2*f);
    delay(5);
    tone(beep_pin,f);
    delay(5);
  }
}
void risefall()
{
  float rise_fall_time=180;
  int steps=50;
  float f_max=2600;
  float f_min=1000;
  float delay_time=rise_fall_time/steps;
  float step_size=(f_max-f_min)/steps;
  for (float f =f_min;f<f_max;f+=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
   for (float f =f_max;f>f_min;f-=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
}
void fall(float rise_fall_time)
{
  int steps=50;
  float f_max=2000;
  float f_min=500;
  float delay_time=rise_fall_time/steps;
  float step_size=0.97;
  for (float f =f_max;f>f_min;f*=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
}
void rise()
{
  float rise_fall_time=2000;
  int steps=100;
  float f_max=1500;
  float f_min=500;
  float delay_time=rise_fall_time/steps;
  float step_size=1.012;
  for (float f =f_min;f<f_max;f*=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
  noTone(beep_pin);
  delay(100);

}

void twotone()
{
  float f_max=1500;
  float f_min=1000;
  float delay_time=800;
  tone(beep_pin,f_max);
  delay(delay_time);
  tone(beep_pin,f_min);
  delay(delay_time);

}
void loop() {
  // put your main code here, to run repeatedly:

  for (int count=1;count<=10;count++)
  {
    risefall();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<=10;count++)
  {
    fall(300);
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<=5;count++)
  {
    fall(600);
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<5;count++)
  {
    rise();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<5;count++)
  {
    twotone();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<10;count++)
  {
    zap1();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<10;count++)
  {
    zap2();
  }
  noTone(beep_pin);
  delay(gap);
}

It's also on GitHub, and released into the public domain under the unlicense so anyone can use it however they like


Cannot find Arduino under /dev Directory I have the Arduino board connected to a USB port of my machine. But I cannot find it under /dev/ directory in my Ubuntu. Does anyone know how to deal with this issue? By the way, "lsusb"'s output proves that it has been recognized. Here is the output of this command:

Bus 002 Device 002: ID 8087:8000 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 007: ID 413c:2105 Dell Computer Corp. Model L100 Keyboard
Bus 003 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Here is the output of ls -l /dev/ttyACM*

ls: cannot access /dev/ttyACM*: No such file or directory

and the dmesg output when disconnect and reconnect the device:

[1653809.002715] usb 3-11: USB disconnect, device number 13
[1653832.188835] usb 3-11: new full-speed USB device number 14 using xhci_hcd
[1653832.211392] usb 3-11: New USB device found, idVendor=2341, idProduct=0043
[1653832.218400] usb 3-11: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[1653832.226003] usb 3-11: Manufacturer: Arduino (www.arduino.cc)
[1653832.231859] usb 3-11: SerialNumber: 85235353137351708191
[1653832.237468] usb 3-11: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes

Note that lsusb does not guarantee the drives are loaded (See https://superuser.com/questions/165733/will-lsusb-and-lspci-list-devices-for-which-the-system-has-no-drivers)

Per the https://stackoverflow.com/a/14586884/1653571 answer, try an 'lsmod' and see whether you have a 'cdc_acm' module loaded.


How do I pull up D1-D6 using 10k ohm resistors? I'm using push buttons to control CR servos (button1=turn CW; button2=turn CCW). How do I pull up D1-D6 and what does that do exactly? I can't find a tutorial that explains it well enough how to use the resistors.

Typical Atmel AVR inputs can “float” when left open, that is, may drift high or low.  The idea of a pullup or pulldown resistor is to give an otherwise-open input a definite value – high if pulled up, low if pulled down.

The values of pullup and pulldown resistor values are a tradeoff:   You can use high values to minimize the current that a sensor device must overcome when it switches values, and to minimize power loss in a battery-powered device.  Or you can use low values to get faster switching when you release the input.

There are built-in pullup resistors on most AVR inputs.  (But A6 and A7 on some models of ATmega328's don't have pullups.)  To use a built-in pullup, initialize the input pin with (for example) pinMode(mypin, INPUT_PULLUP) instead of pinMode(mypin, INPUT).

To sense the state of a simple normally-open switch, you would connect one side of the switch to an input, and the other side to ground.  Initialize the pin to be a pulled-up input: eg, pinMode(mypin, INPUT_PULLUP).  Regard the switch as not-pushed when digitalRead() shows HIGH, and  pushed when it shows LOW.

If you really want to use external pullup resistors, connect the switch as above – one side to ground, one side to a pin – and connect a resistor between +5 V and the pin.  That is, one end of a resistor and one side of a switch will connect to the input pin.  In this case, use either INPUT or INPUT_PULLUP as the pinMode setting; it makes no big difference because the internal pullup resistor has a fairly high value, eg 40 KΩ.


Send data before raising edge of a Clock I'm trying to control a LED strip that has a custom protocol (developed above of I2C).

But in my tests i was successful figuring out how it works :

You set Clk to zero , you send a bit in the data line , then you set Clk to high. Based on the pixels number , i should send 16bits for each color (Red Green Blue).

I was able to generate a Clock signal at 8MHz with this code :

const byte Clock = 9;
const byte Data = 10;

void setup ()
{
 pinMode (Clock, OUTPUT);
 pinMode (Data, OUTPUT);
 digitalWrite(Data, HIGH);
 TCCR1A = bit (COM1A0);
 TCCR1B = bit (WGM12) | bit (CS10);
 OCR1A =  0;
 }

 void loop ()
 {
 ...
 }

My questions :
How could i send data at that specific time when the clock is at zero ?

Note that using digitalWrite() function was not working due to the frequency limitation of that function.

Thanks for any helpful information.

It sounds like you have some misconceptions.

In order to work with clocked signals like in SPI, you set your data line(s) to the desired value, and then raise the clock signal from low to high. The receiving device detects the low to high transition and reads the state of the data lines.

If you did it in the other order (switch the clock signal from low to high, then set the data pin(s).) then the receiver would detect the clock rising edge and try to read the data value before it was set correctly.

With a clock line like in your setup, the communication doesn't rely on fixed timing. The clock line tells the receiver when the data is available, and you can use whatever clock timing you want (up to the max speed supported by the hardware.)


ACS712 to build doorbell sensor - Arduino Hangs up I have a ACS712 module that I am connecting to my Arduino Uno to read the current spike when my door bells rings (and then trigger some events in my "sketch").

In my country doorbells use the ~115 VAC at ~60Hz. So, I just opened the doorbell and connected the ACS712 module in series.

I do not know how much amperage my doorbell draws, but it is hardly the 30A supposedly supported by the module.

At this point I am not connecting the OUT pin to the Arduino, only VCC and GND to the +5V and GND of the Arduino Uno. (I am also tried connecting the OUT pin to A2 in the Arduino).

What happens is that as soon as I ring the doorbell the Arduino hangs up. Sometimes I even have to physically unplug the Arduino to get it back to life.

It doesn't necessarily happens in the first bell, but it does not survive 3 rings in a row.

The ACS712 chip is supposed to provide 2.1 kVRMS of isolation... it doesn't seem likely that the "kickback" from the bell would be 2100 VAC... so I cannot imagine how/why my Arduino is hanging up, when it is supposed to be completely isolated from the AC (that's the whole point of the Hall Effect current sensor).

I added some capacitors to the VCC/GND pins with no luck.

So... any ideas on 1) how to protect the Arduino from hanging up?, 2) what is making the Arduino hang up?.

There are two probable solutions to your problem:

The ACS712 is a hall effect based sensor and also door bells have a solenoid attracting a hammer to hit the bell. Try and place the sensor away from the bell, this could avoid any possible magnetic interference. (This is less likely to happen but there is a fair amount of chance)
May be, there is a problem with the code OR the laptops USB. Connect the Arduino to the sensor and the OUT pin to an analog input. Run the following code:

  void setup()
  {
     Serial.begin(9600);
  }
  void loop()
  {
     Serial.println(analogRead(A2));
  }

If this doesn't work, probably there's a problem with the sensor or the connections.

Give me more details about your connections, code and post a picture of your project for more help.


Creating an Arduino Tic Tac Toe game I'm trying to create a Tic Tac Toe game using the Arduino Uno. Since the Uno has a limited amount of pins to use, I am trying to see if there is a configuration that would make the project possible.

For the button detection circuit I am using a simple voltage divider and an analog pin. I made the following in a circuit simulator:

Now for the LEDs, since the Uno only hosts 9 pins, and we need 18, we need some sort of wizardry to get something working. I came up with the following design using the circuit simulator:

I would use 9 of these, one connected per Arduino pin. Since only one of the LEDs in each of the 9 sets should be on, this type of circuit should allow the Arduino to control all of the 18 LEDs. In the simulation I get about 5mA draw from each side (with 5v and GND).

However my problem is that the LED setup doesn't work. The lights are extremely dim. At first I simply thought that 5mA was not enough for the LED. I decided to measure the current going through the LED and found that it was about 0.8mA. What happened to my 5mA calculation? After all, isn't Arduino pin able to handle about 40mA? Am I asking for too much current?

Where have I gone wrong with this? Thanks in advance for any help.

tommis15

I was working with it more and I found that my mistake was that I was using pin 0 and 1 to test (serial) and switching to pin 2 and above works.


Button state changing randomly I have a push button wired to my Arduino but it seems to be triggering randomly.

I have one pin of the button connected to pin 2 on the arduino and the other connected to ground.

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

    pinMode(2, INPUT);
}

void loop() {
    Serial.println(digitalRead(2));
}

I expect it to print 1 continuously and go to 0 when I press the button down but sometimes it shows 0 even when I don't touch it.

When a button is connected in that configuration, the input is what's called floating, meaning it's not a 0 or a 1. When the button is pressed, it is connected to ground, so that's definitely a 0, but when it's not pressed down, we don't know the value of the pin.

Pull Up Resistor

We need to include what's called a "pull-up" resistor to pull the signal up to a logic 1 when the button is not pressed.

Image from Sparkfun

What this means is when the button is not pressed, the Arduino reads a logic 1. When the button is pressed, the current flows through the resistor to ground and the Arduino reads a logic 0.

Internal Pull Up Resistor

The Arduino also has internal pull up resistors so you don't necessarily have to add an extra component to your circuit. There are a couple of ways to use this.

You used to have to do it like this:

pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors

Now we can do it simply in one line:

pinMode(pin, INPUT_PULLUP);

This enables the 20k pull up resistor on that pin. The input will no longer be floating when the button is not pressed.

Note: This only works when the other end is connected to ground.