Control solenoid valve with arduino running on battery I built a simple setup according to this tutorial using a 9v battery (in the meantime replaced it with a 120A battery):
https://www.bc-robotics.com/tutorials/controlling-a-solenoid-valve-with-arduino/

Also i attached a humiditiy sensor to measure the soil-humidity.
My plan is:
2 times a day (evening and morning before sunrise) wake up arduino and check humidity, if it is below a certain %, open the 12v-valve, wich i operate at 9v (like the one in the tutorial).

I read a lot about how to reduce power on the arduino and found this tutorial for the pro mini, wich seems a LOT easier than to modify the standard arduino uno:
https://www.whizzy.org/2015/06/howto-very-low-power-usage-on-pro-mini-v2-arduino-clone/

Now, my question is:
would a pro mini v2 work as well for controlling the valve? On the uno, i have the vin-pin wich provides the 9v for the valve, on the pro mini instead, as far as i understood, i need to use that pin (named RAW pin there) as power supply for the arduino... but how would i get out the 9v from the arduino like i did on the uno? Is there any possibility at all?

Thanks in advance!

Vin and the barrel jack are the same power input on Uno.

RAW is the label for Vin on Mini Pro.

You can connect the + of the battery to power rail of the breadboard and from there to Vin/RAW pin of Arduino and to the solenoid powering contact.


Help me determine the power consumption/rating of the circuit below? Please help me determine the circuit's power consumption from the battery and help me outline the steps to calculate?

It's not a simple matter of "calculating the power". Instead you need to:

Calculate (or obtain) the current consumption of each individual sub-module or component
Calculate (or obtain) the current consumption of the main MCU for each power state it operates in
Calculate the current consumption of static items such as voltage dividers and power LED

Then:

For each unit examine the percentage of time it spends in different power states. From that create an hourly average current for the unit.

And finally:

Sum up all the average hourly usages to get a final AH value for the whole circuit.

Most of the current values can be obtained either by calculation (e.g., Ohm's Law for resistive dividers and LEDs, etc), or from the datasheets for the devices you have attached.

Note that this will still only be an approximation, because (amongst other things) you have multiple power sources which will cause different drains on the system depending on which source is being actively used (different monitoring circuitry and components switched it), and that (I assume) is influenced by the weather.


Making a PID Controller for BAR 30 pressure sensor I am having issues with my PID controller  for a BAR 30 depth sensor. The issue that I have is my ESC have two initial start up { 1500 - 1900} is min - max respectively clockwise and { 1500-1900} is max respectively counter clockwise.
What I want is for me to set a depth and I can submerge to a certain depth and lock in at that certain depth.

#include <PID_v1.h>
#include <MS5837.h>
#include <Wire.h>
#include <Servo.h>
MS5837 sensor;
Servo vertical_thruster1;

// Variables

float current_depth ;
float set_depth = 0.50 ; //  depth u wish to go in meters
float PID_error = 0;
float previous_error = 0;
float elapsedTime,  Time , timePrev;
double pwmvertical_thruster1 = 1440;

int s;

float PID_value = 0;
float PID_p = 0;
float PID_d = 0;
float PID_i = 0;
//PID constants
float kp = 100;
float ki = 0.003;
float kd = 5.2;

void setup() {
  Serial.begin(9600);
 vertical_thruster1.attach(4);
   vertical_thruster1.writeMicroseconds(1500);

 Time = millis ();

 ///Bar 30 Configuration

  Serial.println("Starting");
  Wire.begin();
 while (!sensor.init()) {
Serial.println("Init failed!");
Serial.println("Are SDA/SCL connected correctly?");
Serial.println("Blue Robotics Bar30: White=SDA, Green=SCL");
Serial.println("\n\n\n");
delay(2000);
  }
  sensor.setModel(MS5837::MS5837_30BA);
  sensor.setFluidDensity(997); // kg/m^3 (freshwater, 1029 for seawater)
}

void loop() {

///*
// First read the current value of the depth sensor
sensor.read();
current_depth = sensor.depth();

timePrev = Time;
Time= millis();
elapsedTime = ( Time - timePrev) / 1000;

// calculate the error between the set depth and current depth
 PID_error =  set_depth - current_depth ;

 // Calculate the P Value
 PID_p = kp * PID_error;
   Serial.print("PID_p: ");
    Serial.print(PID_p);
    Serial. println ( "\t\t");
// Calculate the i value in a range on +-0.3

 if (-0.2 < PID_error < 0.2)
 {
  PID_i = PID_i + (ki * PID_error);
 }
Serial.print("PID_i: ");
Serial.print(PID_i);
Serial. println ( "\t\t");
// Calculate the d value
 PID_d = kd*((PID_error - previous_error)/elapsedTime);
Serial.print("PID_d: ");
Serial.print(PID_d);
Serial. println ( "\t\t");
// The total PID value
PID_value = (PID_p + PID_i + PID_d) ;

// range for the blue robotics esc

if ( PID_value < -150)
 {
 PID_value = -150;
  }
  if( PID_value >150)
  {
  PID_value = 150;

  }
  Serial.print("PID_value: ");
  Serial.print(PID_value);
  Serial. println ( "\t\t");
 // calcualte the pwm

 s =  (pwmvertical_thruster1 + PID_value  );
 if(s < 1350)
{
 s= 1450;

}
else if(s> 1650)
{
  s=1550;

}
  Serial.print("Depth: ");
  Serial.print(sensor.depth());
  Serial.println(" m");
  Serial.print ( "Speed s  ");
  vertical_thruster1.writeMicroseconds(s);
  Serial.print( s) ;
  Serial. println ( "\t\t");
  previous_error = PID_error;
  //  */
  delay(300);
 }

A PID controller should be a good match for your application, but it appears that your code doesn't take advantage of the PID_v1 library at all; a PID_v1 object is never declared, and it appears you are attempting to manually compute what the PID library is designed to do for you automatically.

I would recommend you 'start slow and simple' by learning how to use a PID controller in its most basic form.  The PID library has a very basic example, which I have modified slightly to demonstrate how a PID controller works.  I tested this example with a UNO, a potentiometer (variable resistor) and a capacitor. The resistor and capacitor values aren't critical - I used the first things I found in my parts box.  The output on Pin 3 is a PWM pulse train signal, and the resistor/capacitor combination filters this pulse train to a variable level analog signal, which the PID controller sees as the analog 'Input' on A5.

Once you have this running, you can vary the pot value to see how the PID changes the output value in order to achieve the setpoint value on the input, and you can vary the setpoint and PID parameters to play around with different configurations.  Once you are comfortable with basic PID operation, you should then be able to configure it properly for your application.

Hope this helps,

#include <PID.h>

 //Define Variables we'll be connecting to
double Setpoint, Input, Output;

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

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

    //initialize the variables we're linked to
    //Input = analogRead(0);
    Input = analogRead(A5);  //I used A5 as A0 was unavailable
    Setpoint = 100;

    //turn the PID on
    myPID.SetMode(AUTOMATIC);
}

void loop()
{
    //Input = analogRead(0);
    Input = analogRead(A5); //I used A5 as A0 was unavailable
    myPID.Compute();
    analogWrite(3, Output);
    Serial.print("Input = "); Serial.print(Input); Serial.print(", Output = "); Serial.println(Output);
    delay(100);

}


Force TCNT to stay below OCRxA on ATmega328P I'm using a timer and the TIMERx_COMPA ISR to generate a signal in "the background".

This ISR is triggered when the timer reaches a certain value (OCRxA), which in turn can be changed by the user.
Once the ISR triggers, the timer is reset and the next waiting period occurs.

If the compare value (OCRxA) is changed to a value below the current timer value before having hit the old compare value, the timer keeps running until it overflows back to 0 and hits the new OCRxA value. This results in no signal being generated until the timer has looped around, which can be quite long for the 16-bit TIMER1 timer.

There are multiple way to get around this:

Reset TCNTx to zero whenever OCRxA. Easy, but one signal will always be off-clock
If TCNTx is greater than OCRxA (after changing OCRxA), reset it to just below OCRxA
If TCNTx is greater than OCRxA, trigger the interrupt manually, where the signal is generated and TCNTx is reset

I belive the third option would be the cleanest, both in checking whether the issue has occured as well as for the signal quality.

This is certainly an X -> Y problem, so I'm open for other approaches.

My question, for now, would be:
Can I manually jump to an ISR regardless of its "normal" trigger?

Can I manually jump to an ISR regardless of its "normal" trigger?

This should be possible, but is probably not the best solution.

  This is certainly an X -> Y problem, so I'm open for other
  approaches.

It would seem you are using the timer in CTC mode. In this mode, when
you write to OCRxA, the register is updated immediately, which leads
to the problem you are experiencing. The solution is to instead set the
timer to “fast PWM” mode. In fast PWM mode, the OCRxA register is
double buffered: you will be actually writing to a buffer register, and
OCRxA is automatically updated from that buffer on the same timer
clock cycle that clears the counter.

It may sound counter-intuitive to use a PWM mode when you do not need
the PWM feature. However, as long as the “compare output mode” is set to
“normal port operation” for both channels, the timer will not generate
any PWM output, and you can legitimately use the fast PWM mode only for
its double buffer feature.


Regarding running multiple functions using millis I have been writing code for measuring when the digital signal comes and goes (ON and OFF respectively). I have done the part calculating a single system's downtime (difference in timings between ON and OFF from the system), but when I'm not able to scale up to multiple systems when I try to copy the same code which worked above. So it would be helpful if anyone could provide some insight into how it can be done plus explaining with the code would help.

My code:

unsigned long a=0, b=0, difference;
void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT);
  Serial.print("start");
  Serial.print(",");
  Serial.print("stop");
  Serial.print(",");
  Serial.print("minutes");
  Serial.print(",");
  Serial.println("seconds");
}

void loop()
{
 //delay(1000);
 int A = digitalRead(2);
 if(A == LOW)
 {
  b = millis();
 }
 if(A == HIGH)
  {
     a = millis();
     display_output();
   }
 delay(3000);
}
void display_output()
{
 int minutes, seconds, sec;
 difference = a - b;
 seconds = int(difference/1000);
 if(seconds >= 60)
 {
  //sec = seconds;
  seconds = seconds%60;
  minutes = minutes+1;
 }
 //minutes = int(seconds/60);
 Serial.print((a/1000)+1);
 Serial.print(",");
 Serial.print((b/1000)+1);
 Serial.print(",");
// Serial.print(difference);
 //Serial.print(",");
 Serial.print(minutes);
 Serial.print(",");
 Serial.println(seconds);
 //Serial.println(",");
}

First of all, you should notice there is a problem with your logic:

 int A = digitalRead(2);
 if(A == LOW)
 {
  b = millis();
 }

Here you are testing the state of the pin. If it's LOW you take a
record of the time. This is wrong. What you want to record is the time
at which the inputs falls, not when it's LOW.
This is called state change detection. In order to implement
it, you have to compare the pin state that you just read with
the previous state. The correct condition is “if the pin was HIGH
last time I read it and is now LOW”:

// Global variable:
int pin_state = HIGH;

// Within loop():
int new_pin_state = digitalRead(2);
if (pin_state == HIGH && new_pin_state == LOW) {  // it just fell
    time_of_fall = millis();
    pin_state = new_pin_state;
}

Note that this assumes that the default state is HIGH. If the pin
turns out to be LOW at power-up, then the code will assume it just
fell when the program started.

Next, you have to remove any occurrence of delay() from your code.
That will only make your timings wrong. At this point you have
non-blocking code that can easily be adapted to handle multiple input
channels.

Then you have to identify the variables that are channel-specific, and
have a per-channel version of each variable (arrays are useful here).
Then your code only needs to loop through the arrays.

Instead of having multiples arrays, you can make the code cleaner by
grouping all the channel-specific data into a single data structure:

struct Channel {
    byte pin;
    byte state;
    unsigned long fell, rose;  // times of fall and rise
};

This way you can have a single array that holds all the data for all the
channels:

const int CHANNEL_COUNT = 5;

Channel channels[CHANNEL_COUNT] = {
    { 2, HIGH, 0, 0 },
    { 3, HIGH, 0, 0 },
    { 4, HIGH, 0, 0 },
    { 5, HIGH, 0, 0 },
    { 6, HIGH, 0, 0 }
};

The code now becomes quite simple: you just loop through the array and
handle one channel at a time:

void setup()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i) {
        pinMode(channels[i].pin, INPUT);
    }
    Serial.begin(9600);
    Serial.println("pin,fell,rose,low time");
}

void loop()
{
    for (int i = 0; i < CHANNEL_COUNT; ++i) {
        Channel &c = channels[i];
        byte new_state = digitalRead(c.pin);
        if (c.state == HIGH && new_state == LOW) {  // input fell
            c.fell = millis();
        }
        else if (c.state == LOW && new_state == HIGH) {  // input rose
            c.rose = millis();
            display_channel(c);
        }
        c.state = new_state;
    }
}

The function display_channel() is left as an exercise to the reader
;-) (hint: it's prototype should be
void display_channel(const Channel &c); in order to avoid
unnecessarily copying the data structure.

Next step in code modularity would be to turn the Channel structure
into a class with a proper constructor, and make display_channel() a
method of that class.


Is it possible to control a 12v led matrix with an arduino? This is a bit home automation but if I want to control my 12v LEDs and I have 8 free pins would it be possible to drive 16 lights as a matrix. I was looking into running 8 LEDs with an 8 channel relay but the I got to thinking if I wire up 16 LEDs in a matrix I could still control them all with those 8 channels. Problem is I was looking at mechanical relays that would burn out very quickly with that kind of switching. Are there any other solutions?

You can use ULN2803 driver IC on sink side (cathode), P channel MOSFET on anode/source side of common anode LED matrix. Since you need only 4 sinks you can pair every 2 i/o of ULN2803 so you can drive/sink 1A max load per row. This IC is cheap and widely available.

MOSFET current and speed should match those of ULN2803. You can use BJT instead of MOSFET, but voltage drop on BJT will be higher.

Similar design is here: 8x8 LED matrix


avrdude ser_open() can't set com-state When trying to upload the blink sketch to my (unofficial) Arduino Uno, I get the following error:

avrdude ser_open() can't set com-state for "\\.\COM3"

I have programmed this Arduino before using this same laptop, but not for quite some time.  I have not changed anything in the Arduino IDE in this time.

I have tried the following:

Reading answers for the following related questions:

avrdude: ser_open(): can't set com-state for "\\.\COM2"
avrdude: ser_open(): can't open device "\\.\COM3"?
Can't upload to my Arduino UNO
avrdude: ser_open(): can't open device "\\.\COM4": Access denied

Confirmed that COM3 was the correct port by going to device manager. I have only one port listed here, COM3, and it disappears when I unplug my Uno and reappears when I plug it back in again.  One strange thing to point out is that it is called RAMPS for some reason?
Tried 3 different USB cables
Tried 3 different USB ports
Restarting the computer
Uninstalled and reinstalled the Arduino IDE
Uninstalled the device from Device Manager
Tried a (previously untested) (also unofficial) Arduino Nano.  When I looked up this in Device Manager, it was also reported as RAMPS on COM3 (strange?)

None of the above fixed the issue and all gave the same error as shown above (except when trying different USB ports which showed the error just for different COM ports).

EDIT: Just tried both the Uno and Nano on another computer and both worked fine. This confirms that both the arduinos and cables I'm using are working properly.

Maybe a Windows driver problem.
Do your uno and nano use a ch340? (It is the component translating USB to uart (serial pins of atmega328).
Windows has no software way to differenciate boards using this component. It is a common use on cheap clones to lower price.
Official arduinos use a second atmega (atmega16u2 natively supporting usb) instead of the ch340. Allowing windows to identify the arduino model.

You should try to update your ch340 driver as you have the same problem with the 2 boards. here is the download page of the manufacturer (ch341ser.exe is the package you want)

You can also try to connect your board to an usb2 port as some problems (and solutions to try) are posted here (arduino forum)
And even try to use an usb2 hub...


Detecting a 2.8ms pulse using a Arduino Uno I am working on a project for knowing the position of a DC motor which has a hall sensor built into it. I am a newbie into programming using the Arduino Uno R3. After some forum search and self checks, I cannot pass this hurdle. I hope I can frame the questions properly here.

My Problem: The DC motor hall sensor sends out 2 high pulse of 11.3V - 13V with a duration of 2.8ms for each revolution. My Arduino interrupt pin doesn't read the high pulse as it gives me "0" count after motor spin (I run 50 loops and results remain the same).

On my breadboard, I use a voltage divider to reduce hall-effect ouput from max 13V to 5V so that the Arduino pin 2 can read rising voltage when it jumps to 5V (low should be 2.5V).

Couple of things I noted during the motor spin -

a) The millis() function returns 79-81ms per sketch run

b) The same hall sensor output if connected to analog pin reads 580,590,590,1001, 1012, 580, 580.. etc. I cannot gauge position of the motor by using these values as they are inconsistent on the way up Vs. way down.

I have attached analog readings while going up and down in snap shot below:

2 questions I have:

Why is the pin 2 not detecting a high pulse? will it not be able to read 2.8ms durations because of motor speed (9.5 rev/s or 570rpm)?
Is it possible to gauge anything from Analog read function? Am I missing something?

Thanks in advance for all responses.. Any questions regarding the circuit, I will be more than happy to post them.

First, better to see whole source and schematics.

"Why is the pin 2 not detecting"

Check:
1. Hall sensor connected to Pin 2

pulses variable declared as volatile.
Check if internal pull up resistor setup consistent with hall sensor connection.
Check that Hall sensor's lowest signal voltage is below 0.3 VCC (you said 5V, so it should drop below 1.5V), BTW 580 - the lowest analog value you showed means 2.83V
Check you are not using nointerrupt();

"Is it possible to gauge anything from Analog read function? Am "

Yes.
Analog read takes about 0.1 ms in default setup, so should make at least 1000 reads per second to catch peak.

So,
Easiest way is to choose some value like 600, when analog read is above mark it as Rising when it drops below mark is Falling.
More complicated ways will include some training and hysteresis to improve detection.

Also I suggest to use voltage limiter instead of voltage divider. This gives better detection.


Powering a 5V Arduino Pro Mini with 3.3V I want to run the 5V board at 3.3V because I can get the 5V version cheaper than the 3.3V version.

I read that you can power the Arduino Pro Mini with a battery by connecting the battery to the 5V pin, bypassing the regulator.

Somewhere else I read that the only difference between a 3.3V and 5V Pro Mini is the regulator.

Are these assumptions correct? If yes, can I use a 5V Pro Mini like a 3.3V by powering it with a 3V Battery on the 5V pin?

Pro Mini 5V has voltage regulator for 5V and 16MHz quartz.
Pro Mini 3.3V has voltage regulator for 3.3V and 12MHz quartz.

According to manufacturer specification Atmega328 chip powered by 3.3V cannot run 16MHz and needs at most about 13MHz. But it's official specification. Some chips are better than specification (faster) some are worse (slower). So you can try whether your Pro Mini is better or not. Or you can change quartz to 12MHz, if you can solder SMD parts.

Or better look for cheaper 3.3V clone, they are not much more expensive as 5V version...


Communicating with Arduino In this Question how does the code Processing work?
Which programming language is it written in? How to run it?

"Processing" is a simplified programming language/environment based on Java. It's designed to be very easy for non-programmers to use, and is quite a popular choice for using alongside Arduino projects.

You can download it for free (and get lots of tutorials/documentation) from here:

https://processing.org

As a side note, the Arduino IDE was based on Processing, so it will probably look familiar!


How to store incoming serial data to char array in order to send to other module (XBee)? I am trying to get the incoming serial data in Arduino from a GPS. I suppose to get the following data:

  $GPRMC,073522.000,A,2607.5285,N,12739.9649,E,0.43,263.10,131217,,,A*6C

However, it is not stable. Following is the code. Appreciate your help.

#include <SoftwareSerial.h>
SoftwareSerial gps(2, 3); // RX, TX
int N = 70; // size of array
char incomingSerialData[70]; //32
int incomingSerialDataIndex = 0;

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

void loop() {
  while(gps.available()) {
    delay(10);
    incomingSerialData[incomingSerialDataIndex] = gps.read();
    incomingSerialDataIndex++;
    if (incomingSerialDataIndex > N-1) incomingSerialDataIndex = 0;
  }
  Serial.println(incomingSerialData);
}

NMEA sentences cannot be longer than 80 visible characters + terminators. Even with a CRLF, that's a max of 82 characters. You should be fine with a fixed-sized char array of 82.


Arduino Uno - MQTT message using PUBSUB on ESP8266 I'm trying to write code involving MQTT messages to operate an ESP8266 relay ( a Sonoff device ), using PubSub library.

For some, unknown for me, reason - messages larger than 99 chars are not sent. It this a known limitation ? can it be changed ?

void pub_msg(char *inmsg){
        char tmpmsg[255];
        // sprintf(tmpmsg,"[Cl:oc:k] [%s] %s",deviceTopic, inmsg);   ---> wish to add a time stamp
        sprintf(tmpmsg,"[][%s] %s",deviceTopic, inmsg);  ---> using this line just to find that 99 chars sent OK
        Serial.print("published MSG:");
        Serial.println(tmpmsg);
        Serial.print("Total chars:");
        Serial.println(strlen(tmpmsg));
        client.publish(msgTopic, tmpmsg);

}

The maximum MQTT packet size in PubSubClient is 128 bytes. After all the MQTT header information that leaves only 99 bytes for a message.

You can change it by editing the PubSubClient.h file:

#ifndef MQTT_MAX_PACKET_SIZE
#define MQTT_MAX_PACKET_SIZE 128
#endif

As it says in the PubSubClient README.md:

  The maximum message size, including header, is 128 bytes by default. This is configurable via MQTT_MAX_PACKET_SIZE in PubSubClient.h.


Can't stop my variable value at zero? In my recent project, I want to set my time according to the requirement. And somehow I'm able to manage that. But when I'm decreasing my time value then one weird problem happens. When decreasing my time value, when I reach ZERO (0) and when I again decrease value then it shows the maximum range of that data type even if I put the condition for stop value at ZERO(0).

My code is below:

const int kPinSw1 = 2;
const int kPinSw2 = 3;

int plusBtnIncState = 0;
int lastPlusBtnIncState = 0;

int minusBtnDecState = 0;
int lastMinusBtnDecState = 0;

unsigned long currentMillis;
unsigned long previousMillis;
unsigned long interval = 0UL;

void setup() {
  Serial.begin(9600);
  pinMode(kPinSw1, INPUT_PULLUP);
  pinMode(kPinSw2, INPUT_PULLUP);
}

void loop() {
  //---------------INC_TIMER---------------//
  plusBtnIncState = digitalRead(kPinSw1);
  if(plusBtnIncState != lastPlusBtnIncState) {
    if(plusBtnIncState == HIGH) {
      interval = interval + 1000;
    }
    delay(50);
  }
  lastPlusBtnIncState = plusBtnIncState;

  //---------------DEC_TIMER---------------//
  minusBtnDecState = digitalRead(kPinSw2);
  if(minusBtnDecState != lastMinusBtnDecState) {
    if(minusBtnDecState == HIGH) {
      interval = interval - 1000;
      if(interval <= 0) {
        interval = 0;
      }
    }
    delay(50);
  }
  lastMinusBtnDecState = minusBtnDecState;

  //---------------------------------------//
  Serial.print("Int:");
  Serial.print(interval);
  Serial.print("\n");
}

And output:

Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:2000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:1000
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:0
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296
Int:4294966296

As you can see in output when I reach ZERO and then again decrease the value then the value is like 4294966296 instead of ZERO. I put the logic for that if we reached ZERO or less ZERO then it must stay at ZERO. I don't understand why this happens. Please suggest me something.

The interval variable is unsigned long.

In this example, we are using int that are 4 bits long (just to keep thing short) just to subtract 1 from 0:

    0b0000
   -0b0001
    ------
    0b1111

That is normal arithmetic, but in binary.

The result 0b1111 can read as a signed int, in which case we read the value '-1', or you can read as unsigned, and you read it as '15'.

The same thing is working in your case, only that your int are 32 bits long.

The unsigned keyword is not a promise that "0-1" will produce "0". It only indicates that whatever bit configuration is inside that variable, it will be treat as a positive value.


How to set PC (Program Counter) register to another function (for scheduler) I am trying to implement a scheduler for Arduino Mega 2560. I think I lack understanding of how to set the PC register to another instruction.
Here is my simple approach so far:

void dummy(){
    digitalWrite(LED_BUILTIN, HIGH);
 }

in a naked ISR method:

SP = (uint16_t)(&dummy)
__asm volatile(
"reti     \n\t"
)

However it is not working. How should the PC register be set to a certain function or to where it was in a previous process for a scheduler approach?

This:
SP = (uint16_t)(&dummy)

is changing the stack pointer. Not what you want. You want to instead
push the destination address to the stack. However, rather than
simulating a function return, it should be simpler to perform an
indirect jump:
asm volatile("ijmp" :: "z"(dummy));

Don't forget that your naked ISR has to save all the call-used
registers, as well as SREG, r0 and r1, in its custom prologue. And
restore them in its epilogue. Check the AVR calling
conventions.


How Add Piezo Buzz to Pong Sketch I am junior high teacher teaching students how to program using Arduino. I know the basics of programing but the students wanted to program a game which is a little above my skill set. I am using the following sketch (http://www.itopen.it/arduino-pong-with-8x8-led-matrix-and-max7219/) to introduce them to programing games. Thanks to this site I understand most of the code. However I would like to add a line of code that will make a piezo buzzer buzz every time the "ball" hits the pad. I think the code should look something like the code bellow, but I am not sure if it is correct or where I would put it.

#define buz 8 // number of pin buzzer connected to
     if (HIT_CENTER || HIT_RIGHT || HIT_LEFT) {
        digitalWrite(buz, HIGH);
        delay(100);
        digiralWrite(buz, LOW);
        }

Any help would be appreciated.

The condition HIT_CENTER || HIT_RIGHT || HIT_LEFT will always be true.  (All three of those HIT_ values are non-zero constants.)

Instead, you need to test if getHit() is non-zero.  (To see this, search the sketch for occurrences of HIT_RIGHT or HIT_LEFT.)

The sketch sets up an event timer (via ball_timer = timer.every(BALL_DELAY, moveBall); in setup()) so that ball position will update every 200 ms.  The loop() sequence is: Use timer.update() to service timer events.  Use setPad() to read the paddle position.  Use drawGame() to update the game picture. Somehow use checkLoose() to see if game is over.  Use delay(GAME_DELAY) to wait 10 ms.

Given that structure of loop(), throwing in a 100 ms delay to wait for a buzzer would mess up the game play.  You could turn on the buzzer and set up a timer event for turning it off, each time the ball hits the paddle.

More straightforwardly, since a 10 ms beep is likely to be adequately long, you could test for a hit just before delay(GAME_DELAY), and always turn the buzzer off just after that delay.  In other words, before the delay say:
if (getHit()) digitalWrite(buz, HIGH); and after the delay say digitalWrite(buz, LOW);.

This supposes that writing HIGH to buz turns on the buzzer and that writing LOW turns it off.


Light sensor always getting max value I have build a simple voltage divider with a light resistor and a 5.6k resistor. I am reading the input on A0 on my arduino board but it is almost always at 1023, independent of light. If I cover it it might go down to 1020 but not more than that.

Do I have to use a greater resistor than 5.6k to achieve more difference in the sensor?

The light sensor is similar to this: http://www.ebay.com/itm/20x-5549CDS-Photo-Light-Dependent-Sensitive-Resistor-Photoresistor-LDR-Photocell-/281425650814?pt=LH_DefaultDomain_0&hash=item418646a47e

I think that the resistance is pending between 1k-10k.

The circuit is like this image:

Where Vin is 5V from the arduino. R1 is the light sensor, R2 is 5.6k and Vout is connected to A0.

What have you selected as the analog reference? And if 'external', what is connected to the Vref pin?

For the LDR resistances of 10K and 1K, you  Vout should be ~ 1.8v at 10K, and ~ 4.2v at 1K, and giving A/D readings of somewhere around 370 counts and 860 counts, respectively, with a 5v analog reference.

If your analog reference selected to the 1.1v internal reference, either LDR resistance should give you the max reading, but an LDR = 20K could give just over a volt and pretty close to the reading you're getting.


how to build rc transmitter and receiver with an old rc transmitter I've got an Arduino Mega, an Arduino Nano, two NRF24L01 wireless modules and a old Multiplex Transmitter system.

I want to get the PWM signal and send it to the other arduino which should control the servos and the motor controller.

Is there a good instruction or know somebody how to do that easily?

I need it for a rc plane and the range should be 1km.

If you are controlling an RC plane, you should probably just buy a transmitter and receiver specifically designed for that. They are cheap and reliable and will generate PWM signals on their own.

If you must use an Arduino for some reason, NRF24L01 are not going to cut it as they are not powerful enough to reach 1 km. You should probably look into something like an XBee Series 1. With about 60 mW transmit power, its range is up to 1.6 km.


Using an Arduino to drive a digital RGB LED strip I recently purchased a 5M strip of digital RGB LEDs, that is compatible with the "Adafruit_NeoPixel.h" library.

Is maintaining the original order of the LEDs important?  Could I cut the strip in say four sections, and then reconnect those sections out of their original order?

Just to be clear these are digital 3-pin(+5V,DI,GRN) strips, not analog 4-pin(+12V, R, G, B) strips.

I'm just not finding good info regarding if the individual LEDs are pre-assigned an ID by the manufacturer, or if they somehow use a serial-timing way to assign IDs at startup.

Before digging through the Adafruit_NeoPixel.h, I wanted to see if I could get a quicker answer here.

THANKS!

I can not find detailed information regarding the 5M LED strips you bought.

I have used Adafruit addressable LED strips.  What Adafruit publishes on their web site helped a great deal when I cut my strips into smaller sizes.

Here is an Adafruit image which may help you:

I would think the order does not matter.  But you do need to connect the data such that "outs" go to "ins".  And you need to connect them in a row.  That is you need to connect them in one loop.

Added later...

Assuming we are using the WS2812:

We know from the specifications that the RGB data is encoded as 3 8 bit NZR (Non Zero Return) pulses.  8 bits for each color: red, green & blue.  That there is 1 such "word" of 24 bits for each pixel.  That the beginning of a set of "words" is marked by a 50us or grater interval where DI is zero.  And that each pixel strips off the first 24 bit "word" before passing the balance of the data on.

In other words, it doesn't matter what order WS2812 are assembled in.  Also that WS2812 have no idea where they are in the sequence.  All that matters is that each succeeding WS2812 gets its data from the previous WS2812.

One last note. The necessary timing is really fast and really tight. Can't be more than 150 billionths of a second off. No way can a multitasking platform like a PC, Mac or RaspberryPi pull this off.  When sending off a set of "words" to a string of pixels, the embedded processor will likely not be doing anything else!


The L LED Keeps Itself On I am using a Arduino Uno 3 for line follower robot. However when I power the Arduino Uno, the L led is turned on and is never turned off. After a bit of searching I found out that the L LED is connected to pin 13. So I set the pin 13 to low but still the led is on. Is there a problem with the arduino? Or there's something that I am unaware about? (Amongst a lot of other things that I don't know.)

This is a “feature” introduced in the revision 3 of the Uno board. Up to
Rev 2, the “L” LED was connected to pin 13, through a 1 kΩ
resistor. On Rev 3, the same LED+resistor combination is driven by pin
13 through an op-amp. Thus, when pin 13 is in high impedance mode (i.e.
INPUT mode, the default mode when the program starts), the input of
the op-amp is floating. The voltage at this input (and thus at the
output) is not controlled and depends only on the parasitic conductances
and on leakage currents.

If you want to turn the LED off, you not only need to write LOW to it,
you also (and most importantly) should set the pin to OUTPUT.


Issue with adding a library: No such file or directory I downloaded a Library called "Morse" which I got from the Arduino website:

http://arduino.cc/en/Hacking/LibraryTutorial

(all the way at the bottom of the page there is a link called Morse.zip)
And basically added the library. Then when I import the library, it is included to the sketch. However when I try verifying it, the following error message appears:

to see the image clearer you can right click it and click on "Open image in new tab"

Basically it says:

In file included from sketch_nov28a.ino:1:
C:\Users\Marko\Documents\Arduino\libraries\Morse/Morse.h:10:22: error: WProgram.h: No such file or directory

Now I tried reinstalling the Arduino IDE, I tried adding the library again as well as using the manual method that was stated in that first link above, and the error persists.

What I did notice was that in that second line of the error message, something caught my eye: "...\Morse/Morse.h:10:22:..."
There is a forward slash!(/) Now it seems weird to me that with would happen, especially given that all the other examples I saw of this error online have a backslash (\). This could be the problem.... but even if it is, how do I fix it? I tried going to preferences... does anyone know?

That library is for the older version of the Arduino ide. To fix this you need to open Morse.h and change WProgram.h to Arduino.h.


Is there any better choice other than using delay() for a 6 hours delay? I am designing this incubator system and I need to drive a motor forward and reverse every 6 hours. Is there any better choice other than using delay(). A 6 hours delay seems a little unprofessional.

Several options here, and a couple folks have pointed out some challenges.
"Best" answer -- probably to use a real-time clock (RTC) board to assist your timing, and effectively set a target time (next motor run is at 23:14...) each time the cycle restarts.  By saving this target off (to the EEPROM or an SD card for instance), you'd protect against a potential shutdown and reset of the arduino in the middle.
Secondary answer; set your loop() to include a relatively short delay() statement, then check the elapsed time since the last motor engagement.  This would allow you to have other items processing, as someone else noted in this thread.  This I've pseudocoded below.
unsigned long lastMotorRunTime;

void loop()
{
    /*
     * do whatever
     */
    if(millis()-lastMotorRunTime > 21600000)  // 6 hours have passed
    {
         runTheMotor(); // placeholder for the motor movements you need
         lastMotorRunTime = millis();
    }
   /*
    * do other stuff
    */
   delay(100); // loop about every 1/10 second, or whatever works
}

Given you don't seem to need detailed precision -- a few seconds either way wouldn't matter -- this should work reasonably.  Note it WILL fail if the Ardiuno is reset -- then it will only (in my pseudocode) rotate the motor 6 hours after the last Arduino reset.  Probably better to assume that an arduino reset means move the motor 'now', if the point is to ensure periodic motion rather than precise timing.
For precise timing, as noted, the RTC would be required.
(Updated: Changed lastMotorRunTime to unsigned long)


NodeMCU vin pin(5v) is not working I'm a newbie on Arduino and NodeMCU so now I'm trying to run  my relay module trough the NodeMCU v3  and so far I have wired them all respectively as the instruction below:

NodeMCU
5v Relay

D2
+

Gnd
-

VIN
S

but somehow it doesn't work when I try vin pin but the led of  Relay module just turns automatically on when I connected to 3v pin  works on vin3 without me doing anything through the app (Blynk).
I wonder if I'm missing something here?
Thanks very much for your help in advance.
Sani

You’ve probably switched some wires.
Relay Connection with Arduino, usually takes 3 Pins:

VCC / In (5v)
Signal (Data) - [D2] Pin On your sketch.
Ground

It is that simple.
Some recommendations apart from your question:

Make sure to know how your relay starts.
That is: Starts Always On or Always Off.

On your sketch (relay initialisation); set the initial relay state before defining its function as OUTPUT.

...
digitalWrite(relayPin; LOW);
PinMode(relayPin, OUTPUT);

...

Ensure the wires are properly connected to avoid wasting time understanding why the relay doesn’t work.
Special attention to Ground Wiring.

Note: Depending on your schematic; You may require to bridge your Grounds.


Suggestions for a program for drawing simple schematics I'm wondering if there are free programs or web sites that let you draw simple schematics similar to this example:

A compilation of possibilities mentioned the comments. I'll add to this as I try out the suggestions.

From @Gerben, "kind of in order of complexity":

circuitlab.com - online schematic capture and simulator (analog, digital, and mixed signal). Licensed for professional, student/educator, and hobbyist (free) usage. Officially runs in Chrome and Firefox, and they report users having success with Safari and Opera which are not officially supported.
Fritzing - cross-platform (Mac, Windows, Linux). Has Breadboard View mode with built in Arduino support that allows you to create diagrams like this one:

From there you can click on the Schematic view to route wires and convert the breadboard into a traditional schematic.
CircuitMaker - Windows only, requires creating an account.
Eagle - cross-platform (Mac, Windows, Linux), paid and free versions.

Component library collections (thanks to Marko Mackic for the idea):

Adafruit
Element14 Arduino library - requires registration, lots of other libraries as well
Sparkfun

KiCad - cross-platform (Mac, Linux (with packages for several distributions), Windows, and source code), open source and also on GitHub.

Found Autodesk's 123D Circuits in a question on Arduino Simulators (and emulators).


Most precise way to measure Linear distance travelled by a wheel Suppose a bot with wheels is traveling in a a straight line,and we want to measure this linear distance traversed by it as accurately as possible.
One of the ways is to use an optical encoder to measure the angle of rotation of the wheels and get the linear distance traveled. Another way could be to use the data from accelerometer and get the linear distance traveled. Which of these two methods would be better ? Or,is there a third method which is more precise than the previous two?

If you measure  one of the free running wheels (with no motor connect to it), it depends on the traction of the wheel, but that could be fairly accurate.
If you move horizontally a simple accellerometer (1 axis) would be great. But if you have a vertical component, then you can not distinct between accelleration and weight force (Einstein). If you use a 3 axes accellerometer, you can compute/extract the robots moving speed (subtract the G component = 9.81 m/s²) and thus the distance. You have to use vector arithmetic in this case.
If the ground has enough "structure" you could use an optical sensor (like optical mice have).
If you have a reference object (e.g. a wall, a book) you could use a LIDAR sensor (https://en.wikipedia.org/wiki/Lidar) to measure the absolute distances at time points and compute the relative distance between these time points.


nRF24L01+ module fried? I have 2 nRF24L01+ modules that were working fine then...stopped. I'm wondering if I accidentally fried one of the modules.

When I run the RF24 library GettingStarted example, this is the output of the module I believe may be fried:

RF24/examples/GettingStarted/
ROLE: Pong back
*** PRESS 'T' to begin transmitting to the other node
STATUS        = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1  = 0x0000000000 0x0000000000
RX_ADDR_P2-5  = 0x00 0x00 0x00 0x00
TX_ADDR       = 0x0000000000
RX_PW_P0-6    = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA         = 0x00
EN_RXADDR     = 0x00
RF_CH         = 0x00
RF_SETUP      = 0x00
CONFIG        = 0x00
DYNPD/FEATURE = 0x00 0x00
Data Rate     = 1MBPS
Model         = nRF24L01
CRC Length    = Disabled
PA Power      = PA_MIN

I've changed out cables and connections all the way through. I also replaced this module with the other one directly and the other worked fine.

So, my question: Is this output showing definitively that I've killed the module and just need to buy a new one? Or is there some way to "flash" or reset the module?

Assuming you have triple checked all your wiring before posting this question you should add a small capacitor between Vcc and GND near the nRF24: anything between 10uF and 100uF will do.

Rationale: these devices draw quite a decent amount of current when bootstrapping and transmitting and if they don't receive enough juice they just reset themselves showing those all zeroes settings.

They are pretty robust devices, not that easy to fry.


Light Powered Motor Troubles I'm working on a small car (<1 kg) which will drive when there is light and stop when there isn't. Below is a plan with code drawn up (the only numbers I know for sure are the current gains for the TIP31C transistor and the rated load current of the 6 V motor I'm using). I'm going to map the analog voltages to a digital signal output.

I read that the maximum digital output was 40 mA and also that analogWrite gives a pulse width modulation (PWM) which can be set to 100% (255) [the code: outputval/1], 50% (127) [the code: outputval/2]. I'm concerned with the lack of control I have here over the current. Will Arduino by default draw 7.75 mA maximum if the input signal is high [giving the output signal also as high]? If not, can I control the current in this manner reliably? Also are there anything I should worry about if I added another 6 V motor in parallel? Coding and electrical suggestions greatly welcomed.

TIP31 transistor: http://www.hobbytronics.co.uk/datasheets/TIP31.pdf

6 V dc motor: http://www.kysanelectronics.com/graphics/RF-370CA-22170.pdf

maximum digital output: https://www.arduino.cc/en/Tutorial/DigitalPins

PWM: https://www.arduino.cc/en/Tutorial/PWM

The code:

const int transistorbase = 9;
void setup() {
  //set the base as digital output:
  pinMode(transistorbase, OUTPUT);
}
void loop() {
  //read voltage at divider:
  int inputval=analogRead(A0);
  //map voltage to digital
  int outputval=map(inputval,0,1023,0,255);
  //control transistor:
  analogWrite(transistorbase,outputval);
}

tl;dr
Codewise, how do I control the digital output current to my needs? Am I seeing ghosts?

I would take a simple n-channel MOSFET like this one. At 5V on the gate it can drive up to 8A (so you have plenty of space to connect other motors as long as your power source can handle this) and because it is a MOSFET you don't have to draw much current from the Arduino (only enough to load the gate of the MOSFET). You can also hold the current under the critical value for your motor with a simple resistor (fit for the resulting power dissipation) in series.

Yes, the output of the PWM is 5V - the operation voltage of the Arduino. The whole point in PWM is to use only the digital values (here 0V and 5V) and varying so fast, that slow systems as the motor cannot follow this motion, but summing over the impulses. So the motor gets only very fast kicks. And for a normal motor you don't need fast PWM. This only increases the frequency response from the MOSFET.

The code seems for to me.


Moving a character around an LCD screen - is there a better way? I have some basic programming experience but I am a novice at both C and Arduino.

I messed around with the example LCD code to try to move a character around with the onboard keypad. I also wanted the actual move to occur only once the button is released, like you would expect from a keypad.

The code works, but I have a feeling all the empty WHILE loops inside the main loop() function I used are not the best practice.. :)

How did I do? Is there a more convenient/elegant solution I missed and can learn from?

Thanks, and sorry for the messy code!

void loop()
{
  lcd.clear();
  lcd.setCursor(posCol,posRow);      //initialized beforehand
  lcd.print("O");                    //random char to move
  lcdOld = btnNONE;

  while (read_LCD_buttons() == btnNONE)     //do nothing while nothing is pressed
  {
  }

  lcdOld = read_LCD_buttons();

  while (read_LCD_buttons() == lcdOld)     //do nothing while button is down
  {
  }

  switch (lcdOld)               // depending on which button was pushed, we perform an action
   {
   case btnRIGHT:
     {
     posCol++;
     break;
     }
   case btnLEFT:
     {
     posCol--;
     break;
     }
   case btnUP:
     {
     if (posRow == 1)
     {
        posRow = 0;
        break;
     }
     else
     {
     break;
     }
     }
   case btnDOWN:
     {
     if (posRow == 0)
     {
        posRow = 1;
        break;
     }
     else
     {
     break;
     }
     }
   case btnSELECT:
     {
     break;
     }
     case btnNONE:
     {
     break;
     }
 }
}

You could encapsulate the logic of detecting a button release into its
own function:

// Return the button that was just released, or btnNONE.
int releasedButton()
{
    static int last_button = btnNONE;
    int previous_button = last_button;
    last_button = read_LCD_buttons();
    if (last_button == btnNONE)
        return previous_button;
    else
        return btnNONE;
}

Then the logic in the loo gets simplified:

void loop()
{
    switch (releasedButton()) {
        ...
    }
}


When uploading a sketch to an esp8266, isn't that the same as "flashing firmware"? I thought that I read that using a PC running the Arduino IDE to "upload a sketch" to an esp8266 overwrites the original firmware (with the AT commands), and is actually "flashing the firmware" each time a "sketch" is uploaded. If I have that right, then why does the esp8266 WiFi still visible in available connections? There must be some code instructing the esp8266 to do this, but where is it? My sketch was simply the hello blinky thing and contained no #include statements. Where have I slipped?

Uploading a "sketch" is indeed "flashing firmware".

  why does the esp8266 WiFi still visible in available connections?

I'm not sure what you mean by that.


Webpage values wont update I've been trying to run the following esp32 LED PWM code to change the LED's brightness, and show the current PWM duty on the webpage, but the PWM values on the webpage won't change until I hit the submit button twice.

#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
WebServer ser(80);
int s=0;
String k;

String iso()
{
  k="
LED PWM<FORM action=\"/\" method=\"post\"><input type=\"text\" name=\"duty\">
 <input type=\"submit\" value=\"Submit\">Cureent Duty=";
  k=k+s;
  k=k+"
";

  return k;
}

void root()
{
  iso();
  ser.send(200, "text/html", iso());

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());
  }
}

void setup() {
  Serial.begin(9600);
  ledcAttachPin(33, 4);
  ledcSetup(4, 5000, 8);
  WiFi.begin("ssid", "pass");
  Serial.print("\nConnecting To WiFi");
  while (WiFi.status()!=WL_CONNECTED)
  {

    Serial.printf("\n.");
  }
  Serial.print("\nConnected");

  ser.on("/", root);
  ser.begin(80);
}

void loop() {
  ser.handleClient();
}

Here's a GIF addressing the issue

When the client sends you a request, you should answer only once. Your
root() function attempts to answer twice whenever the request contains
the argument “duty”. The client will not handle a duplicate response to
a single request.

Here is your root() function:

void root()
{
  iso();
  ser.send(200, "text/html", iso());  // ← first response

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());  // ← second response
  }
}

You may notice that the first response was sent before updating the
duty cycle.

The proper way to handle the request is to first handle the request
parameters, if any, then send the response:

void root()
{
  if (ser.hasArg("duty")) {
    s = ser.arg("duty").toInt();
    ledcWrite(4, s);
  }
  ser.send(200, "text/html", iso());  // ← only sent once
}

As a side note, there is absolutely no need to build the response five
times (you have five calls to iso() within root()) when you only
need it once!


Arduino IDE - Maximum serial COM ports What is the maximum number of serial ports (com) can Arduino IDE detect ?

I need to connect 6 Arduino UNO Wi-fi at a time to make a small network and I use a 7 port USB hub for the same. The device manager shows 6 com ports detected but Arduino shows only 4 serial ports detected. Is there a limitation on the serial ports interfaced with the Arduino IDE ?

According to the last version of code for Arduino IDE, there are no limits of discovered Serial or Network devices since they are stored in a list (not limited as an array).

To discard problems, try with another operating system.


Controlling a DC motor with an external power source I'm trying to use an Arduino to release a single drop of water using a solenoid valve.  This article describes how to create this circuit with a Raspberry Pi using a DC powered solenoid that opens and closes very quickly and they use this for photographing water drops.  Exactly what I need, if I could only get it to work with the starter kit items first.

The design for the solenoid circuit from that site looks like:

I don't have a solenoid yet, but I've been experimenting with the cheap motor that comes with the Arduino and a 9 V battery.  I've burned out several transistors in my attempts to get this working.  My schematic looks like:

Relays won't work.  They are too slow.  Also, I need to use an external battery.  I can't use the power from the Arduino because I will eventually be moving up to a 12 V battery and the Arduino won't be able to handle that.

Seeing as you want to use a 12V battery, you should try an external motor controller. You would essentially connect the Arduino to the controller, then the external battery and motor to the controller. Dimension Engineering makes several high quality motor controllers that are compatible with Arduino and can handle the voltage (like this controller). The site also includes Arduino libraries, documentation, and all the specifications on every product. I have used several of their products with my Arduino Uno and have had no problems.


pinout for stm32duino with bluepill I am running the blinking LED program with stm32duino, and an STM32.  By trial and error, and a bit of debugging, I have worked out the following:

pin C13 blinks as well as the built in LED
(except my external LED is on the built-in LED is off)
the constant LED_BUILTIN equals 17

I found this pinout: https://stm32duinoforum.com/forum/wordpress/wp-content/uploads/2016/07/The-Generic-STM32F103-Pinout-Diagram.pdf

But it says nothing about C13 being pin 17.
Does anybody know where to look to find out where the arduino pins line up to the codes on the board?

OK if this helps anybody, they give you constants for every pin that look like PC14 for the one that says C14, so you don't need to worry about the integers that they assign to the pins.
I mean there are constants named for the yellow boxes on the above diagram.


Help with code. Fade in LEDs from off (shift register) I used this tutorial here and decided it to overcomplicate the pattern. For further learning. My code in theory should start the LEDs at a low brightness and fade them in using this code. My expected output is as follows.

All 8 LEDs start out as off.
Fade in slowly.
LEDs turn of one by one from left to right.
LEDs turn on one by one right to left.
Fade out.
Repeat.

This is the loop that fades the LEDs in.
for (byte b = 1; b < 255; b++) {
  setBrightnessUp(b); //sets the brightness up function
  delay(20);
}

This is the function:
void setBrightnessUp(byte brightness) {// 0 to 255
  analogWrite(outputEnablePin, brightness);
}

However at this time it appears to be getting into my loop but not increasing the brightness at all. When the code first runs, the LEDs are on but at a minimum brightness. The rest of the code including the fade out at the end works fine.
Fade out functions:
for (byte b = 255; b > 0; b--) {
  setBrightness(b); //sets the brightness function
  delay(20);
}

void setBrightness(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, 255 - brightness);
}

Here is the complete code. Excuse the over commenting it helps me learn:
//sets pin out for control pins on shift register

int latchPin = 5;
int clockPin = 6;
int dataPin = 4;
int outputEnablePin = 3; //enables a PWM pin output

//uses byte (8bit binary variable)
byte leds = 0;

void setup() {
  // sets the pins to output mode
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode (outputEnablePin, OUTPUT);
}

void loop() {
  //attempted to make led fade in from 0
  leds = 0; // set led to no output ready for dimming effect
  updateShiftRegister(); //calls the function used for output
  delay(1000); //troubleshooting delay
  for (byte b = 1; b < 255; b++) {
    setBrightnessUp(b); //calls the brightnessup function
    delay(20);
  }
  leds = 255; //Sets the byte variable to 255 or 11111111
  updateShiftRegister(); //calls the function used for output
  delay(500); //waits 1/2 second

  //sets a variable i at 8 and runs while i is more than 1
  //minus 1 each loop
  for (int i = 8; i > -1 ; i--) {
    //Bitclear acts on a byte like its an array
    //it sets the bit at position i to 0 (or off)
    // the left most bit is 7 the right most 0
    bitClear(leds, i);
    updateShiftRegister(); //calls the display function
    delay(250); // waits
  }
  //sets a veriable i at 0 and runs while is less than 8
  //plus 1 each loop
  for (int i = 0; i < 8 ; i++) {
    //same as bitclear but turns on the bit at position i
    bitSet(leds, i);
    updateShiftRegister(); //calls the display function
    delay(250); //waits
  }
  //After the 2 other for loops are finished this will then fade
  //the LEDs out
  //sets the bite to 255 (11111111), while its more that 0
  //and minus 1 each loop
  for (byte b = 255; b > 0; b--) {
    setBrightness(b); //calls the brightness function
    delay(20);
  }
}

// this function outputs the data to the shifter
void updateShiftRegister() {
  digitalWrite(latchPin, LOW);//sets the latch pin to low(off)
  shiftOut(dataPin, clockPin, LSBFIRST, leds);
  // the first 2 functions set the data and clock pins needed
  //to receive data. The LSBFIRST tells it to start at the right
  //most bit (MSBFIRST is oposite). LEDs is our binary array (byte)
  // EG 0000000 would print no lights. It shifts this into the
  //shiftregister at 1 bit at a time from one end or the other
  //(determined by LSBFIRST or MSBFIRST)
  digitalWrite(latchPin, HIGH);  // sets the latch pin to high
  //the low to high state change triggers the output
}

//brightness down slowly
void setBrightness(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, 255 - brightness);
}

//supposed to fade the brightness up
void setBrightnessUp(byte brightness) { // 0 to 255
  analogWrite(outputEnablePin, brightness);
}

Board layout

I was mistakenly thinking that setting the brightness variable to 255 would mean that the LED is full on. This is wrong, 255 is actually off.

So with a little change in my code.

for (byte b = 255; b > 0; b--) {
  setBrightnessUp(b); //calls the brightnessup function
  delay(30);
}

The loop now works. I am still not sure why 255 is off and not on though.


ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function This question comes on the heels of this question
In the last question I learned how to use an initializer list to solve my issue, but working with ros::Subscriber is requiring a different solution.
I'm dealing with a callback in this scenario. If I leave the callback as a standalone function then the program runs but I have no access to class members and methods inside the function which defeats the purpose. Here is my standalone callback:
void setPRYCallback( const std_msgs::Empty& toggle_msg) {}

Once I move this into my class is when I encounter the error.
steps to implementing into class
// add member variable for callback
protected:
  void setPRYCallback( const std_msgs::Empty& );

...

// ass method
void ROSController::setPRYCallback( const std_msgs::Empty& toggle_msg) {}

...

// set initializer list
ROSController::ROSController() : sub("setPRY", &setPRYCallback )

How do I thwart this error while keeping my callback as a class method?
Program with Standalone Function Callback (program runs)
#include <ros.h> // https://github.com/ros-drivers/rosserial/blob/jade-devel/rosserial_arduino/src/ros_lib/ros.h
#include <std_msgs/Empty.h>

class ROSController {
  protected:
    ros::Subscriber<std_msgs::Empty> sub;
    ros::NodeHandle _nh;
  public:
    void loop();
    ROSController();
};

void setPRYCallback( const std_msgs::Empty& toggle_msg) {}

ROSController::ROSController()  {
  this->_nh.initNode();
  this->_nh.subscribe(sub);
}

void ROSController::loop() {
  this->_nh.spinOnce();
  delay(1000);
}

Program with Method Callback (program fails)
#include <ros.h> // https://github.com/ros-drivers/rosserial/blob/jade-devel/rosserial_arduino/src/ros_lib/ros.h
#include <std_msgs/Empty.h>

class ROSController {
  protected:
    ros::Subscriber<std_msgs::Empty> sub;
    ros::NodeHandle _nh;
    void setPRYCallback( const std_msgs::Empty& );
  public:
    void loop();
    ROSController();
};

void ROSController::setPRYCallback( const std_msgs::Empty& toggle_msg) {}

ROSController::ROSController() : sub("setPRY", &setPRYCallback )  {
  this->_nh.initNode();
  this->_nh.subscribe(sub);
}

void ROSController::loop() {
  this->_nh.spinOnce();
  delay(1000);
}

arduino mega

When you move the setPRUCallback function into your class you change the prototype (well, C++ changes the prototype) from:

void setPRYCallback( const std_msgs::Empty& toggle_msg) {}

to:

void setPRYCallback( ROSController *this, const std_msgs::Empty& toggle_msg) {}

That is now not what the callback registering function expects, and so it breaks.

By making the method static it removes that *this parameter, but also means that the function can only access static data within your class (variables also marked static) and there is only one copy of the function (and static variables) shared between all instances of the class (maybe not what you want).


SIM300cz AT command returns -1 I connected SIM300cz module's GSM board with Arduino Mega. The GSM board has the pins VCC, GND, RXD, TXD, GND, RI, DTR, STATUS, PWKEY and GND. I connected the GNDs with Arduino's GND, VCC to Arduinos 5V (took power from Arduino), RXD to pin 5, TXD to pin 6 (because of using software serial) and PWKEY to pin 53. My code is as follows:

#include<SoftwareSerial.h>
SoftwareSerial GPRS(5, 6);

int inputPinTempSensor = 0;
float tempCelsius = 0 ;
float thresholdTemp = 45;

void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);  // the Serial port of Arduino baud rate.
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);
  delay(100);
}

void loop() {
  GPRS.print("AT+CREG/r");
  Serial.print(GPRS.read());
  delay(2000);
}

The AT command response should be something like "ok" but it's returning -1 for every loop waiting 2 seconds. Why and what could be the solution?

Edit:

Sorry for the mistakes. I was trying different ways with carriage return and new line characters to make it work. Now the code is:

#include<SoftwareSerial.h>
SoftwareSerial GPRS(5, 6);

void setup()
{
  GPRS.begin(9600);               // the GPRS baud rate
  Serial.begin(9600);  // the Serial port of Arduino baud rate.
  pinMode(53, OUTPUT);
  digitalWrite(53, HIGH);
  delay(2000);
  GPRS.println("AT+CREG");
}

void loop() {
  while(GPRS.available()){
    Serial.print(GPRS.read());
  }
}

Now it gives no responses at all. Actually after buying the module I was trying with these examples and they were not working either. So, I thought to test if the AT commands were working properly. I could be a problem with my wiring too.

I think there are 2 mistakes in your code:

First, you should ensure that the 3AT3 commands are termintaed by a new line character:

GPRS.print("AT+CREG/r");

should be changed into:

GPRS.println("AT+CREG/r");

or:

GPRS.print("AT+CREG/r\n");

Nite that I am not sure why you added /r at the end of the AT command, is that supposed to be part of the command? If your intention was to force a new line, then you meant \r not /r, which is not really a new line character but a carriage return (that might be interpreted the same by yur GSM module, but not necessarily).

The the second mistake in your code, is directly calling GPRS.read() without first waiting for a character to be available; in this situation, GPRS.read() will always return -1 as a specific value meaning "no available character to read".

So you should change your code to something like:

// 1st wait for a character to be available
while (!GPRS.available()) {
}
// Then read all available characters and log them to Serial
while (GPRS.available()) {
    Serial.print(GPRS.read());
}


Help putting an Arduino project on the Internet I'm working on quite a big project and I need few advices. Basically, Arduino will be receiving data (Strings) and will work with it. No problems with that, but I don't know what to do with receiving and sending data. Customers (all over the country, so the program will not run on LAN) will send the data, but the question is, via what? Application, that will make a TCP connection to Arduino, send UDP packet or maybe a website? Customers need to have access to data (it needs to be refreshed when arduino deletes it too). What would be the most efficient, easy to use and reliable system?

Next thing I want to know is how to make a connection. Open a port on router and connect arduino to that router? I currently have a python script that actually sends an UDP packet to local IP and it works great, but it is limited to LAN. Will it work if I just change the IP (to external) and send it to the port?

And the last thing (for now). I know how to programm in python and java. Which one is better for connections and GUIs?

Thank you for your help, and if you need any more info about the project, I will be happy to edit this post.

What would be the most efficient, easy to use and reliable system?

What seems to me is that you need what is called Unified Application Routing. There are various technologies to do that but what I suggest is WAMP  (Web Applicaton messaging protocol, do not get confused with wamp server stack) but you can check this comparison table and select the one that most helps you. Based on that what I suggest is crossbar.io. Is open source with a lot of examples, runs on small devices (raspberry pi for example) and is intended for the use you propose, connect devices and let users/apps to get/give information from them. You can publish/subcribe to topics and all devices or apps connected with that topic can read it. Imagine something like an arduino is reading temperatures from a room and publish that data to topic "Temp1". All devices(other arduino, servers, esp8266)  or apps(websites, programs, what ever you clients you imagine) that also are connected at that moment to topic "Temp1" will get that update and act like you want. Wamp also provides a nice feature that is called RPC (remote procedure call). Imagine that you want some real nasty thing in your arduino but it lacks memory or is too slow for that. You can create a program that is, lets say in a raspberry, just waiting for that calculation and returns the result to arduino.

Take a look at this video as an example of what you can do with this ttype of techonologies. A lot of demos also in crossbar.io page. The beauty is that you can program in almost any language you are familiar with. They rely on websockets for the majority of things but crossbar is not restricted to it only, you can even use raw sockets.

As for the second part.

If you create your on server (crossbar lets say) inside the lan you have to forward the port he is listening in your router so other outside your network can access it( and possibly will need to get some kind of Dynamic DNS service if your internet provider do not have statics IPs). Or you can host your server outside your network (crossbar has a tutorial for Amazon EC2 and for Microsoft Azure I think). You only need to port forward server ports.
Hwo do you connect arduino? Use ethernet shields, esp8266, choose a yun or make a combo like arduino with usb + raspberry. That way you can also use your raspberry as a crossbar server.

Here is an example of my home made crossbar.io server using 2 python programs , 1 rboard and a raspberry pi has a host to manage my home heating system and the webpage is being accessed from internet, not local lan.


Confusion about PNP transistors I was reading through SparkFun's article on transistors when I came across something that confused me. The article showed this circuit:
With this description:

Similar to the NPN circuit, the base is our input, and the emitter is tied to a constant voltage. This time however, the emitter is tied high, and the load is connected to the transistor on the ground side.
This circuit works just as well as the NPN-based switch, but there’s one huge difference: to turn the load “on” the base must be low. This can cause complications, especially if the load’s high voltage (VCC in this picture) is higher than our control input’s high voltage. For example, this circuit wouldn’t work if you were trying to use a 5V-operating Arduino to switch on a 12V motor. In that case it’d be impossible to turn the switch off because VB would always be less than VE.

I am confused because the part about the Arduino not being able to turn off a PNP transistor makes sense, but doesn't the circuit shown feature exactly the situation described that the transistor wouldn't work in? Is this an oversight by me and is there something else going on here that I don't understand, or is this a mistake in the article?

The article is saying that the circuit wouldn't work, thus it illustrates (correctly) something that won't work. What is the confusion?

To turn the PNP transistor off, the base voltage needs to be low with reference to the emitter voltage. Thus with an emitter voltage of 12V, and the most the Arduino can output is 5V, the transistor will never be off.


How to connect an L293D and an MPU6050 to run together? I'm wondering how to connect the L293D (H-bridge) and an MPU 6050.

I'm using 1 Arduino Uno, 2 DC motors, 1 MPU6050 and an L293D.

When I tried this, I got some sparks/smoke from the breadboard and none of the motors where running. I only used a 9v battery, not 12v.

Here's the L293D:

MPU 6050 wiring: int-digital 2, SDA-A4, SCL-A5, GND-GND, VDD-Vss

L293D wiring: Vss-VDD, Input4-Digital 5, Output4-Motor, Output3-Motor, Input3-Digital 6, Enable2-5V, Enable1-5V, Input1-Digital 9, Output1-motor, Output2-motor, Input2-Digital 10, Vs-12V battery.

There a some mistakes with the wiring of the supply voltage (Vss) according to the datasheet (http://www.ti.com/lit/ds/symlink/l293.pdf) of the L293D a those on pin 8 (Vss2) and 16 (Vss1). I think those are not connected because each Vss is for one motor of the driver. So you have to connect 9V (or 12V) to both pins.
There is also something wrong with the capacitor (polarity). And your connection of the battery to the breadboard is a bit weird because + of the battery is usally the red not the black wire / marked row on the breadboard.


Using millis() to toggle an LED every 500 milliseconds I thought the code below would toggle an LED every 500 milliseconds. But it does not work. I'm not able to catch the mistake, which must be very silly.

void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  unsigned long cnt=millis();
  if(!(cnt % 500)) {
    PORTD^= (1<<PD3);
  }
}

Anyhow the code below works. But why not the previous code?

void loop() {
  static unsigned long prev=0;
  // Note: First time case is not handled. As soon as we want to toggle,
  // we must store millis() in prev. In this case this happens after reset and may not be an issue.
  unsigned long current = millis();
  if((unsigned long)(current - prev) >= 500) {
    PORTD^= (1<<PD3);
    prev = current;
  }
}

if (!(millis() % 500)) ...

There are two issues with this. The first, and most obvious, is that the
condition will be true for a full millisecond. During that millisecond
you will be toggling the LED on and off very fast. Whether you end up
doing an odd or even number of toggles is anyone's guess.

The second and less obvious problem is that millis() skips some
values. Roughly one integer every 42 is skipped over. This is because
the millis() counter is incremented once every 1024 µs, getting
24 µs late on each increment. Once all those delays add up to a
full millisecond, millis() catches up by incrementing the counter by
two milliseconds instead of one. This is why you should never condition
something on millis() having one specific value.

The almost correct solution to this problem is shown in Juraj's answer:

  if (millis() > next) ...

This is not quite correct because it fails each time millis() rolls
over back to zero. The correct solution is

static unsigned long last;
if (millis() - last >= 500) {
    last += 500;
    ...
}

Because the subtraction follows the rules of modular arithmetic, this is
guaranteed to work across the rollover events.


Problem with interpretting and using the IMU data I am using MPU6050 IMU for getting accelerometer and gyro data. I could read the data using the code from the I2Cdev library here, but the problem I have is that I can't use this data in a meaningful manner. As an example I want to define the motion of an object in x,y,z axis using accelerometer data. Although I get a set of values, I can't understand how to use it.

If I could convert these values to ms-2 units, I hope I would be able to achieve this

Could you provide me some advice, code or reference to work on this?

I also tried the code here to get the raw values.

You may want to take a look of freeimu library which take care of all needed processing and present filtered and data-fused data (not just raw data) in easy to use roll, pitch and yaw format.

http://www.varesano.net/projects/hardware/FreeIMU

see demo video in which the on screen data mirror physical motion of the sensor
http://www.youtube.com/watch?feature=player_embedded&v=rFvX3vZJHTQ

hope this helps


how to detect 125khz tags with mfrc 522 I have just ordered MFRC 522 RFID reader from amzon, and I have also orders 5 RFID tags with keychains and a arduino uno board for my project, I have received RFID reader and tags and I have tested the tags with my Sony xperia NFC. The tags that I received with the readers are working fine but the key chain ones are not working. I think because of the frequency difference 13.56 MHz and 125 KHz. So, please tell will this key chain tags work with the Reader

You are correct NFC is 13.56MHz the key chain ones you are referring to are most likely 125kHz The reader you have will only read 13.56MHz this is the NFC and HID cards. If you want to read the Key Chain ones you will need a reader like this one. Weigand 26 Card Reader Most Phones will not read the 125kHz


How to re-solder the resistor in order to reprogram the Atmega8U2 As I see here I need to reprogram the ATMEGA8u2: https://www.arduino.cc/en/Hacking/DFUProgramming8U2 I need to solder a 10k resistor into a specific place.

In a previous attempt I did that and resulted the following marks:

So How I can resolder the resistor in order to reprogram the atmega8u2?

Looks like you ripped a pad off. To prevent that in the future, try using more flux and dropping the temp (Max around 320*C/610*F). The iron shouldn't be in contact with the board for more than about 3 seconds. No force should be necessary to remove components.

Not to worry though. Common beginner's mistake and not too hard to fix.

To prep this for repair:

Gently clean the area up with 91% isopropyl alcohol and cotton swabs.
Carefully scrape away the solder mask (blue paint) on what's left of the copper trace all the way back to the via (little hole). Try to remove all the solder mask from the via. Straighten and flatten the pulled up trace.
Clean, flux, and tin (apply as thin layer of solder) to the trace and remaining pad. Filling in the via is OK as it will give better surface area to attach the repair.
Flux and solder the resistor to the remaining pad to keep it in place and properly aligned for the repair.

To repair the damage:

We need to bridge the gap created by the damaged pad. A globby solder bridge may work, but wire is much better.
Find a piece of thin gauge solid core wire (30-22AWG. Some 24AWG from an ethernet cable would do fine).
Orient the wire so that it's directly over the remaining trace and also making contact with that end of the resistor.
You can trim it to size now or after soldering. It may be easier to keep in place if you trim it after soldering as long as you have some fine flush cut pliers. Either way, leave enough that it covers the entire cleaned and tinned portion of the trace.
Flux and solder the wire to both the resistor and trace. This will complete the circuit.
Clean again with alcohol. Let dry. Test the board.

Give this Adafruit article a read. I've got extensive professional soldering training and endorse it fully as the best beginners soldering guide I've found.


Same code in setup() and loop() give different results As the answers to this question and this one state, setup() and loop() are identical in the way they execute code (apart from the obvious looping function of loop()).

However.

I get different results with following two pieces of code:

Code run once, in setup()

/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

void setup() {
    LED.setOutput(13); // Digital Pin 13

    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Yellow?
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
}

void loop() {
}

Code run once, in loop()

/*
 * light_ws2812 library test
 */

#include <WS2812.h>

WS2812 LED(1); // 1 LED

cRGB value;

bool hasBeenSet = false;

void setup() {
    LED.setOutput(13); // Digital Pin 13
}

void loop() {
  if (hasBeenSet == false){
    value.b = 0; value.g = 0; value.r = 255; // RGB Value -> Red
    LED.set_crgb_at(0, value); // Set value at LED found at index 0
    LED.sync(); // Sends the value to the LED
    hasBeenSet = true;
  }
}

The difference:

The code run in setup() makes the LED flash once with the desired color.
The code run in loop() makes the LED stay lit with the desired color.

With the data being transmitted on pin 13, I can tell (because of the LED on there) in both cases data is being sent only once. With the loop() version I can even disconnect the data line after the color has been set, and it will stay lit.

I can only conclude the same code is executed differently in both cases.

Is there some sort of (soft) power reset after setup()? That could be a potential cause, as the color is stored in volatile memory on the WS2812B (if I'm not mistaken).

Link to the library used: http://github.com/cpldcpu/light_ws2812

After some discussion it turned out to be a hardware problem. For the sake of completeness I'll outline the suggestions I made.

There was some initial confusion (see the edits) where the hasBeenSet flag was initialized the wrong way around.
I could not reproduce the problem on my Uno and my WS2812 chip, so the issue was: what was different between his setup and mine?
Possible wiring issue. Make sure +5V, Gnd and Din (data in) are wired correctly.
Possibly faulty WS2812 chip - try with another one.
Possibly faulty Arduino - try with another one.
Possibly Arduino running at the wrong clock speed which would throw the timings out.
Possible extra components (eg. capacitors) added to the circuit which were throwing timing out.
Possible bug in the library. We eliminated that by trying with my library for Neopixels.

In the end DaJF reported that the problem was solved by using another (or no) breadboard. It seems the breadboard was introducing issues, maybe noise or bad connections.

We never really worked out why doing it in loop rather than setup made such a difference. I can only conclude that the slight timing difference compensated for the bad connections (or capacitance) on the breadboard.

I'm going to stick my neck out a bit and suggest that the capacitance in the breadboard was affecting the "shape" of the signal (we are talking about timings of around 350 ns here). Possibly if you measured with an oscilloscope you would see the problem.


Wifi strength Automation . Help. Noobie here #include <ESP8266WiFi.h>
const char *SSID = "mr_lazy_boei";
const char *pass  = "usalusal";

WiFiClient client;

// Relay pin number
int ignition=2;
int self=0;

//   Return RSSI(Received Signal Strength Indicator) or 0 if target SSID not found
int32_t getRSSI(const char* target_ssid) {
 byte available_networks = WiFi.scanNetworks();

 for (int network = 0; network < available_networks; network++) {
   if (WiFi.SSID(network).compareTo(target_ssid) == 0) {     //stringOne.compareTo(stringTwo) < 0
     return WiFi.RSSI(network);
   }

 }
 return 0;
}

void setup() {
 Serial.begin(115200);
 delay(10);

 Serial.println("Connecting to ");
 Serial.println(SSID);

 WiFi.begin(SSID,pass);
 while(WiFi.status() !=WL_CONNECTED)
 {
   delay(500);
   Serial.print(".");
 }
 Serial.println("");
 Serial.println("WiFi connected");

pinMode(ignition,OUTPUT);
pinMode(self,OUTPUT);
}

void loop(){

int32_t rssi = getRSSI(SSID);

 // For debugging purpose only
 Serial.print("Signal strength: ");
 Serial.print(rssi);
 Serial.println("dBm");

 if (rssi > (-55) && rssi != 0) // if rssi is greater then -55 dbm or it's 0 dbm, then the light will turn
 {
   digitalWrite(ignition, LOW);
   Serial.println("ON");
}
else

{
 digitalWrite(ignition,HIGH);
 Serial.println("OFF");
}
if (rssi > (-55) &&rssi !=0)
{
 digitalWrite(self,LOW);
 delay(750);
 digitalWrite(self,HIGH);
 Serial.println("SELF OFF");

}

}

Above is my code written. As you can see, I have two variables: ignition and self. ignition works the way I want, but the self variable turns on and and then off. That is correct. But it again turns on because of void loop().
Let me explain further:
If wifi signal is strong the ignition should turn on and the self should turn on for less than a second and then turn off. It should not turn on again. When the signal goes weak the ignition turns off. Again, when signal gets strong the ignition turns on and I need self to turn on for not even a second and turn off.
I tried my best getting that. I tried moving it to void setup(), but that just works when I power up the device. After that it doesn't turn on or off. Please kindly help me. I know here I am having very talented brothers who would help me out on this issue.

You need to design your program using a Finite State Machine.
First start off by defining each state that your program can be in, and what is allowed to happen in each of those states.
For example:

IDLE

The only thing that is allowed to happen here is detecting the RSSI and deciding whether or not to start the engine.

IGNITION

The RSSI has got strong enough and you want to start the car. The only thing you want to do is turn on the ignition and wait a moment. Nothing more.

CRANK

Once you've waited a moment you can crank the engine. That means turning on the starter motor and waiting a moment.

RUNNING

Now the engine has started you can release the starter motor and leave the engine to idle. It's now that you want to start watching the RSSI gain.

STOP

The RSSI has dropped below your threshold, so now you can stop the engine.

IDLE

Now the engine's stopped you can go back to the start and idle looking for the RSSI to get high enough again.
These are all the states of a Finite State Machine. You move from state to state depending on different inputs or triggers.  One input is your RSSI value - or more strictly your RSSI value being above or below a threshold.  Another input is (less obviously) time. Waiting for some time to pass.
So you start in state 1. In that state all your program is doing is watching the RSSI. When that rises you move to state 2. At that point it performs whatever actions are needed (turn on the ignition) and record the time. When enough time has elapsed you move on to state 3, and do the same.
It could actually be simplified by compressing states 2 and 3 together:

Turn on ignition
Delay
Turn on starter motor
Delay
Turn off starter motor
Delay
Move to next state

You could then increase the complexity again a little (while increasing the safety) by adding extra steps when you're watching the RSSI. You can then check to see if the RSSI has been above (or below) the threshold for a certain amount of time before moving on to the next step:

IDLE - watching RSSI

If RSSI rises above threshold go to state 2.
Else stay in state 1

Record the time and keep watching the RSSI

If RSSI drops below threshold: Go back to 1.
If Enough time has passed: Go to state 3.
Else stay in state 2

Start the engine.

Go to state 4

RUNNING - watching RSSI

If RSSI falls below threshold go to state 5.

Record the time and keep watching the RSSI

If the RSSI rises above threshold: Go back to 4
If enough time has passed: go to state 6.
Else stay in state 5.

Stop the engine.

Go to state 1.

... etc ...


OLED (I2C) and Micro SD card module not working together in Arduino I am trying to write some data to SD card and read it back to serial monitor as well as display it to the OLED.

Both the sd card and oled work separately but they seem to be interfering with each other when combined. I have used Arduino SD and Adafruit OLED libraries.

Connections from Arduino Uno to Micro SD card module-

5V to SD VCC
GND TO SD GND
PIN 10 TO SD Chip Select
PIN 11 TO SD MOSI
PIN 12 TO SD MISO
PIN 13 TO SD SCK

Connections to OLED-

3.3V to OLED VCC
GND TO OLED GND
A4 TO OLED SDA
A5 TO OLED SCK

Here is the code -

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

File myFile;

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while(!Serial) {
    ;
  }

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // CODE GETS STUCK HERE. DISPLAY NEVER INITIALISES
  }
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(29,29);
  display.print("INITIALISING");
  display.display();
  delay(5000);

  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  myFile = SD.open("test.txt", FILE_WRITE);

  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  display.clearDisplay();

  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
      display.setCursor(0,0);
      display.print(myFile.read());
      display.display();
      delay(5000);
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

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

}

Code gets stuck at OLED initialization as mentiontioned above. If I replace these lines-

if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // CODE GETS STUCK HERE. DISPLAY NEVER INITIALISES
    }

To this-

display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

I have run I2C scanner code on OLED so the address "0X3C" is correct.

The OLED still doesn't work and SD card initialises but arduino is writing wrong data to TXT file on SD card like this-

teóting 1,à2, ó®

Instead of -

testing 1, 2, 3.

I have also tried using U8G2 library's sketches with SD card in case Arduino was running out of RAM but it still doesn't work. I have also changed SD chip select to Arduino digital pin 4 but still same results.

On browsing and experimenting more,I found MISO OR MOSI PIN of SD maybe interfering with SDA/SCL pins of OLED. Maybe wiring needs to change.

ANY SUGGESTIONS???

A pullup resistor is needed for I2C, and adding them might fix some errors.


Timer Prescaler problem I am working on a project which requires use of 16bit timer . I am using Arduino Uno (Atmega 328p) board and Timer_1 (16 bit timer ) in Overflow mode. i want to use 1024 prescaler settings.

According to the datasheet of the controller i have to set [b]CS10 and CS12[/b] bits to use 1024 prescaler but the problem is OverFlow interrupt routine is never fired when 1024 or 256 prescaler is selected .

The Following code works just fine with Prescaler set to 8 or 64.

#include <inttypes.h>

volatile uint8_t sCount = 0;

void setup()
{
      Timer_one_16_init(); // configure the timer

      pinMode(13,OUTPUT);

}

void loop()
{
    // do nothing
}

void Timer_one_16_init(){

    TCCR1A = 0;

    // set the pre-scaler to 1024 (slowest)

    TCCR1B |= (1<<CS12)|(1<<CS10);

    // set the bottom / starting value

    TCNT1 = 0x00;

    // set Overflow interrupt

    TIMSK1 |= (1<<TOIE1);

    // enable global interrupt
    sei();

}

ISR(TIMER1_OVF_vect){

    sCount++;

    if (sCount == 60)
    {
        digitalWrite(13,!digitalRead(13));
        sCount = 0;

    }

}

i have no idea why this is happening. i have done everything which is given in the datasheet .

Am i doing something wrong ?

Thanks in advance

You must write the clock-select bits to the correct value. The simplest
way to do it is to write the proper configuration into the TCCR1B
register:

TCCR1B = (1<<CS12)|(1<<CS10);

In your program, you used |= instead of =. This doesn't write the
bits appropriately: it only sets (writes to 1) the bits CS12 and
CS10 but doesn't clear CS11. Since the Arduino core library sets the
prescaler to 64 (CS11 and CS10 set), you end up with all the
clock-select bits sets, in which case the timer is clocked by an
external signal on the T1 pin. Not what you want.

Edit: Judging from the comments, it appears that at least dannyf did
not understand my answer, I am therefore adding a clarification. There
are two scenarios when you may want to tweak the control registers of a
peripheral:

The peripheral is normally controlled by the Arduino core library,
and you want to use it through that library. Typical case: you want
to use a timer to analogWrite(), or the ADC to analogRead(), but
you want to clock the peripheral at a frequency which is not the
core's default.
You want to use a peripheral directly rather than through the Arduino
core. Either you are going to “take it over” from the core, or it's a
peripheral the core doesn't use in the first place.

In the first case, you should only touch those bits of the control
registers that you must change. The other bits should be left alone, at
whatever values the core has set them to. This is the approach of
dannyf's answer.

In the second case, it is wiser to not rely on the core's default
setting, and instead write every single bit of the control registers
to the values appropriate for your application. This is the scenario of
the original question, and the solution proposed in my answer.

For the particular case of this question, the TCCR1B register would
be set to: ICNC1 = 0†, ICES1 = 0, reserved bit = 0, WGM13
= 0, WGM12 = 0, CS12 = 1, CS11 = 0 and CS10 = 1. Combining those bits
together gives the setting TCCR1B = 0x05;. However, for readability
reasons, I prefer to write that value (1<<CS12)|(1<<CS10), as in the
question and in my original answer. Some people may prefer to explicitly
write every bit, like

TCCR1B = (0<<ICNC1) | (0<<ICES1) | (0<<5)    | (0<<WGM13)
       | (0<<WGM12) | (1<<CS12)  | (0<<CS11) | (1<<CS10);

Whichever version you prefer is up to you. I personally don't find this
latter version any easier to read.

†: The values of ICNC1 and ICES1 are actually
irrelevant in this case.


How to connect new OV7670 FIFO to Arduino? I bought a new OV7670 FIFO camera to connect to my Arduino UNO a few days ago.

The picture of the cam board:

I found this forum, it is nice try but it looks chaotic and confusing with about 50 pages, where you can't find where the questions and where the answers are.

I also found this library which is for non-FIFO board and could not apply to my project. I also read the OV7670_FIFO and OV7670 and AL422 datasheets and I read I2C protocol and basics; and there are many success story on the internet but there is no schematic on them.

The problem is, I can't find any simple example for FIFO with schematic to start with. I don't know if this camera is so new or it is so hard to understand, this problem getting so serious that somebody wrote a book named "Beginning Arduino ov7670 Camera Development" about it, but I think it is a matter of an Arduino to FIFO cam schematic and example code. I ask if there is a such schematic and code for it on the web or how can I connect them?

I recently brought this book off Amazon "Beginning Arduino ov7670 Camera Development".  I'm loathed to recommend it, because it has a nice 80 page introduction to the Arduino and OV7670 and the rest of the 250 pages are just double space annotated code.  That said, it does appear to be a very good introduction, with example code, for a OV7670-FIFO (the title of the book is incorrect).

It might be possible to find the code on the net and then you can decide if you want to buy the book or not.  Oh and I am not Robert Chin, I do not know him and I have nothing to do with the book, other than owning a rather new and once read copy of it.


LED cube and 200 mA limitation I'm new to electronics and have been getting rather into my Arduino. But I don't just like following an instructable to do something. I like to know the math behind it and how it works inside. Now from my understanding the Arduino (Uno R3 for me), has a 200 mA max current. The LEDs I used have a 20 mA current. Now with 64 LEDs, wouldn't this fry my Arduino? This also applies to my LCD screen with a 160 mA current. Am I missing a key secret to going over amperage?

The current limit you quote is the maximum current that the main chip on the Arduino can tolerate through its 5V or GND pins.

As the chip itself consumes (round numbers demonstrate the theory) say 50mA that leaves 150mA in total that can be sourced or sunk through IO pins.

If you want to supply 20mA per LED (that is actually overkill - you can use considerably less and have very little difference in brightness) that means you can have, illuminated at any one time, (150 / 20 = ) 7.5 LEDs.

To increase the number of LEDs you can drive at once you can:

Reduce the current by increasing the resistor values.
Use multiplexing so that, although it looks like all LEDs are on at once, only a few are actually on at once.
Use external LED driving circuitry (transistors, LED driver shift registers, etc).

All this pertains purely to the current that passes through the main chip itself.  It does not pertain to any current you draw from the 5V or 3.3V pins.  The maximum current through those pins is limited by the voltage regulator they are attached to, and also by the voltage that you are supplying the board with (the higher the voltage, the more voltage has to be dropped, and so the more heat is generated per mA drawn).

The 5V regulator has around 800mA limit when supplied with 6.5V.  If supplied with 12V the limit is considerably less (since it will get too hot and go into thermal shutdown).  You subtract what you are drawing through the chip (maximum 200mA) and that is how much current you have available.

The 3.3V regulator is driven from the 5V regulator, so any current drawn from the 3.3V pin must also be subtracted from what is available on the 5V pin.


Error uploading to ATtiny I followed Great Scott's video on YouTube for uploading to an ATtiny85. When I tried I got the following error messages:

Arduino: 1.6.7 (Windows Vista), Board: "ATtiny85 (internal 8 MHz clock)"
Board attiny-master:attiny:attiny85-20 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY85-20
Board attiny-master:attiny:attiny45-8 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY45-8
Board attiny-master:attiny:attiny85-8 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY85-8
Board attiny-master:attiny:attiny44 doesn't define a 'build.board' >preference. Auto-set to: ATTINY_ATTINY44

etc. etc. ...

exec: "-w": executable file not found in %PATH%
Error compiling.`
This report would have more information with
"Show verbose output during compilation"
enabled in File > Preferences.

When I unplug  my ATtiny85 and restart Arduino, I have no problems uploading, though I get about 8 error messages saying something like:

Board attiny-master:attiny:attiny84 doesn't define a 'build.board' preference. Auto-set to: ATTINY_ATTINY84

It's likely that a compiler's file name is missing from a command line the IDE is trying to execute.  To find out more about what the command looks like (which will let you figure out what name is missing), turn on verbose output during compilation.  That is, click File, Preferences in the IDE, then click the box in front of “compilation”.  After you find out what's missing, you can then turn off verbose output and fix platform.txt, which is the file the IDE looks at to find out what commands to execute when compiling sketches.

To get rid of the warnings about undefined build.board values, add lines like the following to the boards.txt file in the tiny/avr/ directory (or whereever you installed it).  (Your 1.6 IDE wants build.board definitions, which IIRC weren't needed by 1.5 and earlier IDEs.)

attiny85-20.build.board=ATTINY_ATTINY85-20

Each of the lines you add will contain the Auto-set value, prefaced by a string made up of a board-type and .build.board= concatenated together.  Add each line just before or after other .build.-containing lines.