Arduino H-bridge for rc car I've got an old rc car laying around, of which i would like to swap the insides, but re-use some of the parts that are already in there. The car runs 2 dc motors: one for steering, one for throttle. The dc motors are both connected to H-bridges in the original setup to make their direction switchable. This is done via 8 transistors. 4 for the throttle and 4 for the steering.
The transistors for steering are 2x S8050 (NPN) and 2x S8550 (PNP).
For throttle it uses 2x 2SD882 (NPN) and 2x 2SB772 (PNP).
I found a schematic in an online post of a arduino H-Bridge setup. It look promising, but it uses 2n4403 and 2n4401 transistors. I was wondering if I could copy the schematic, replace the Arduino 5v power source (as depicted in de schematic) with the battery voltage source of the car, and replace the transistors in the schematic with one pair of the transistors I described above (so 2x 2SD882 and 2x 2SB772 or 2x S8050 and 2x S8550) Would the arduino be able to switch the described transistors? Would the 1K ohm resistors in between the arduino and the transistors suffice?
I am planning on making this schematic twice, once for throttle and once for steering. The throttle output is max 11.5v and the steering uses around 5v. Therefore the throttle circuit would be powered from the battery voltage and the steering circuit would be powered of a 5v regulator.
Can this be done this way?

Just a comment about your diagram. The two transistors should not share an Arduino pin in that way. If the pin is pulled high the transistors saturate and your current 'shoots through' from supply straight to ground. Instead assign one Arduino pin to each transistor (using the base resistor in your diagram).


print data after being plugged back into USB I have an arduino uno powered by a battery on a buggy with a sonar distance sensor.  I have a program that calculates the speed it's going, and I want to correlate speed with stopping distance.  I can measure the stopping distance manually, but I want the arduino to report to me the speed it was going when the motor was turned off.  I don't have an LCD display - I wanted to print the number to the serial monitor, but plugging it back into the USB port resets everything I think, or at least the serial monitor.

Without buying more components, can I get the data (calculated speed) somehow?

You could have it write the final speed to EEPROM after the motor is shut-off, and output this value when the Arduino boots, see:
http://www.arduino.cc/en/Reference/EEPROM


How to read a timer's value once stopped? I've downloaded the Timer1 library but unfortunately it seems that the read() method has been removed from it. I tried also SimpleTimer library from the arduino website but the program didn't compile because of undefined reference to `SimpleTimer::SimpleTimer()' error. Anybody knows how to solve this error or just another timer library which has a read function?

To be more specific I need to start a timer as I press a button and to stop it as it is released.

Here, below is a code which is you looking for. When you pressed a button then a timer is started and when you released it then a timer is stopped. And you can also see that time also means how long button is pressed.

const uint8_t button_pin = 2;

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

void loop()
{
    static int last_button_state = HIGH;
    static unsigned int push_count;
    static unsigned long last_press_time;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if (last_button_state == HIGH && button_state == LOW) {
        push_count++;
        last_press_time = now;
    }

    // Report when the button is released.
    if (last_button_state == LOW && button_state == HIGH) {
        unsigned long push_duration = now - last_press_time;
        if (push_duration < 10) {  // discard bounce
            push_count--;
        }
        else {
            Serial.print(F("pushes: "));
            Serial.print(push_count);
            Serial.print(F(", duration: "));
            Serial.print(push_duration);
            Serial.println(F(" ms"));
        }
    }

    last_button_state = button_state;
}


Arduino Uno with Kubuntu 16.04: Unable to enumerate device I try to connect my arduino uno R1 in order to program the atmega8u2 but I am not able to do so. When I run sudo dfu-programmer atmega8u2 erase I get the following results:

dfu-programmer: no device present.

So in order to diagnose it i run dmeesg with the following results:

 [ 1395.921051] usb 2-3: new full-speed USB device number 30 using
 xhci_hcd [ 1396.041175] usb 2-3: device descriptor read/64, error -71
 [ 1396.269135] usb 2-3: device descriptor read/64, error -71 [
 1396.497109] usb 2-3: new full-speed USB device number 31 using xhci_hcd [ 1396.617169] usb 2-3: device descriptor read/64, error -71
 [ 1396.845177] usb 2-3: device descriptor read/64, error -71 [
 1397.073163] usb 2-3: new full-speed USB device number 32 using xhci_hcd [ 1397.073371] usb 2-3: Device not responding to setup
 address. [ 1397.281311] usb 2-3: Device not responding to setup
 address. [ 1397.489086] usb 2-3: device not accepting address 32,
 error -71 [ 1397.609173] usb 2-3: new full-speed USB device number 33
 using xhci_hcd [ 1397.609382] usb 2-3: Device not responding to setup
 address. [ 1397.817200] usb 2-3: Device not responding to setup
 address. [ 1398.025176] usb 2-3: device not accepting address 33,
 error -71 [ 1398.025235] usb usb2-port3: unable to enumerate USB
 device

Do you know fellows how to make my arduino connect back into my computer?

Furthermore II forgot to mention my user is in dialout group as groups gnu/linux command mentions:

pcmagas adm dialout cdrom sudo dip plugdev lpadmin sambashare libvirtd docker wireshark

PS: That thing happened after soldering the resistor into the board so it is a new problem.

You should solder the resistor (in case you do not have the skills I reccomend doing into a proffessional, a professional close to me managed to solder it with a cost about 5 euros) and then hardware reset the atmega8u2 the documentation mentions. For quick reference just look over in this image:

In the dmesg you will see similar the same or message:

[ 1544.679504] usb 1-6: new full-speed USB device number 42 using xhci_hcd
[ 1544.808341] usb 1-6: New USB device found, idVendor=03eb, idProduct=2ff7
[ 1544.808350] usb 1-6: New USB device strings: Mfr=0, Product=1, SerialNumber=0
[ 1544.808356] usb 1-6: Product: Arduino Uno DFU

Then look on the similar question for R1 boards or in case you have a newer board then follow the instructions mentiones to the documentation.


Programming a motor with an RGB Please see the comments section if confused.
I am trying to turn a motor on and off once per second, and when the motor is on, the RGB turns green. When the motor is off, the RGB is red. Everything is connected to an arduino UNO.I have the motor connected to pins 0 and 1, and to the 5V and GND. The RGB is connected to pins 4, 5, and 6, and the 5V.
I have two codes; one with a bunch of screwing around with a bunch of different loops and everything else I've tried, and one with the simple motor on/off code.

void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
////  pinMode(2,OUTPUT); //IB2
////  pinMode(3,OUTPUT); //IA2
//  pinMode(4,OUTPUT); //RGB
//  pinMode(5,OUTPUT); //RGB
//  pinMode(6,OUTPUT); //RGB
//  pinMode(A0,INPUT); //lMotor
////  pinMode(A1,INPUT); //rMotor
//  Serial.begin(9600);
}

void loop ()
{
  digitalWrite(0,HIGH);
  delay(1000);
  digitalWrite(0,LOW);
  delay(1000);

//  int lMotor = analogRead(A0);
//  Serial.write(lMotor);
////  int lMotor = analogRead(A1);
////  Serial.write(lMotor);
//
//  if (lMotor>10)
//  {
//    digitalWrite(4,HIGH);
//    digitalWrite(5,HIGH);
//    digitalWrite(6,LOW);
//  }
//  else
//  {
//    digitalWrite(4,HIGH);
//    digitalWrite(5,LOW);
//    digitalWrite(6,HIGH);
//  }
}

And here's this:

void setup ()
{
  pinMode(0,OUTPUT);
  pinMode(1,OUTPUT);
}

void loop ()
{
  digitalWrite(0,HIGH);
  delay(1000);
  digitalWrite(0,LOW);
  delay(1000);
}

What do I need to do? Should I use a "while" loop? If so, how?
Is my circuit put together properly? I'm using a motor relay switch to turn the motor on/off, but I'm pretty sure it's hooked up right.
Any help is appreciated, even if it doesn't answer all of my questions.
Thank you.

Try this:

void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT); //RGB red
  pinMode(5,OUTPUT); //RGB green
  pinMode(6,OUTPUT); //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  digitalWrite(0,motorOn);
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
  delay(1000);             // wait
  motorOn = !motorOn;      // toggle the status of the motor.
}

The code above has the disadvantage that the on-time is the same as the off-time. We can make the code more flexible and a little more like your original by doing the LED related code in a subroutine:

void setup ()
{
  pinMode(0,OUTPUT);   //IB1
  pinMode(1,OUTPUT);   //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT);   //RGB red
  pinMode(5,OUTPUT);   //RGB green
  pinMode(6,OUTPUT);   //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  motorOn = false;
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(1000);             // wait
  motorOn = true;          // toggle the status of the motor.
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(750);              // wait a different time
}

void updateLEDs(){
  // This routine updates the LEDs based on status of motorOn.
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
}


PROGMEM doesn't cause Sketch size to change I'm trying to pinpoint some strange behaviour involving the use of PROGMEM and the size of a Sketch.

I've written a library that contains a number of functions, in addition to several large global byte arrays and 32-bit uint arrays. These arrays are stored in PROGMEM using the pgmspace library. The library compiles fine, and all code works properly when uploaded to an Arduino.

I'm performing testing on the functions using a testing sketch that in turn uses my library. In order to test the performance, I've been switching between using PROGMEM and not using PROGMEM in the library (all arrays are under 2KB). When using PROGMEM, it drops the Global Variable dynamic memory count by the expected amount... but the the sketch program size remains either constant, or seems to arbitrarily increase or decrease by a very small amount, depending on the function. For example, a uint8_t byte[256] array, when moved to the PROGMEM, causes the Global Variable size to go down by about 256 bytes... but the sketch size only increases by about 12 bytes.

Each entry in the array is unique and is accessed, so the compiler shouldn't be optimizing it away. I tried just using avr-size directly on the ELF file, but the sketch size was the same. I can't tell if the data is being stored in PROGMEM all the time (even when not declared as PROGMEM, due to some sort of issue with PROGMEM in libraries?), or if PROGMEM data simply isn't being counted as part of the sketch size, or ??? I have tried moving the functions directly out of the library into the sketch, changing data types, adding/removing static and const declarations... but the lack of change in sketch size continues to confuse me. Any help would be greatly appreciated.

all constant data are part of the sketch. where else should they be? in runtime they are loaded into RAM. PROGMEM directive prevents the loading into RAM.


DigitalRead() floating pin problem I am having a problem implementing a the digitalRead() function in arduino uno.I want digitalRead to return 0 when nothing is connected and return 1 when it is connected to +5 volt.But seems like digitalRead returns random values when it is not connected to anything.
I have kind of solved the problem by a small piece of code to stabilize the value i'll attach the code here but if any other solution is avalable..Please help.

The function is as follows:-

bool getValue()

{

String k="";

if(digitalRead(3)==HIGH)

k="HIGH";

else

k="LOW";

bool f=true;

for(int i=0;i<1000;i++)

{
String z;

  if(digitalRead(3)==HIGH)

  z="HIGH";

  else

  z="LOW";

  if(k!=z)

  {

    f=false;

    break;

  }

}

if(f==true)

return true;

else

return false;

}

The solution is called a pull down resistor and it's exactly the same as when you are using a button - the button is what connects the pin to +5V. The pull down resistor (usually around 10kΩ) connected to ground is what makes the pin read LOW at other times.


How to check if a pin is set from bank? How would you go about checking if an input pin has been set using the entire bank? I am thinking that I need to use bit twiddling with a bit mask but I have not used this enough to figure out how to do what I want.

Basically I have the following code:

void setup() {
   DDRA = 0x00;
   PORTA = 0xff;
}

void loop(){
   //Check if any pin from Port A has been pressed
   if (PINA & 0xff){
      //do stuff
   }
}

But the code above is not working how I expected it to. Has anyone tried to use this approach before? Am I going about this the wrong way? I figured since I was using all 8 pins from one bank, it would be better to check if any of the pins on that bank have been set instead of checking each individual pin. My thinking on this was to prevent any user input from being skipped in case a button press was initiated while the program was running other code. This way I only check if anything in the bank has been set saving time (I think).

The problem is here:

//Check if any pin from Port A has been pressed
if (PINA & 0xff){

Since the pullups are enabled, the default state of the pins is high. To detect a "press", they have to be pulled to ground. This changes the test to:

//Check if any pin from Port A has been pressed
if (~PINA) {

And for individual pins:

//Check if PA3 has been pressed
if (!(PINA & _BV(PA3))) {


Arduino mega 2560 might be dead I was playing with Vin and a transistor when the arduino got disconnected from my pc and after a few seconds it started to smoke. It wasn't much smoke but enough to panic and disconnect everything. I waited a few minutes and then i plugged it into my pc. The power led and the 13 pin led were on but my pc couldn't recognize my device. In arduino ide i couldn't find the port and the tx and rx leds didn't blink at all. I tried to restart my px, reset arduino, i powered it with a 12v source and i got 12v out on Vin but 0 on 5V and 3V. The 13 pin doesn't want to turn off and my pc doesn't recognize it. It is not a ch arduino and it worked perfectly until i did this. I've benn searching on internet for 2 hours now about this but i still couldn't find something relevant. In device manager it sais "unknown usb device (device descriptor request failed)" and inside proprieties at device status this is written:

"Windows has stopped this device because it has reported problems. (Code 43)

A request for the USB device descriptor failed."

I also tried to update drivers automatically and manual but didn't work. I have no idea where that smoke came from.

Is it dead? can i do anything to make it work?

i powered it with a 12v source and i got 12v out on Vin but 0 on 5V
  and 3V.

The fuse or the Vin input diode or the 5V voltage regulator or all of them could be damaged.

  i plugged it into my pc. The power led and the 13 pin led were on but
  my pc couldn't recognize my device.  In arduino ide i couldn't find
  the port and the tx and rx leds didn't blink at all.

The MCU could be damaged.
The USB chip is dead (Because there is no rx blinking during programming).

If you connect the arduino through USB and there was not 3.3v at the 3.3v supply rail, the 3.3v voltage regulator is dead.

You had better buy a new one or if you want to fix it to gain experience go for it.


Is there anything special about Arduinos? I've been using the stm32f4 discovery up until now but I've heard Arduinos are easier to use. While looking for an Arduino Genuino Uno Rev3 board, I was told to get a knock off instead.

Is there any real difference between Arduino boards and other knock off micros with similar specs?
I really just want to get a feel for what it's like using an 'easier' micro. It doesn't need to be extra special.

This is Google Trend of Arduino (blue) versus four other boards: STM32 (red), Teensy (green), MSP430 (yellow) and PIC32 (magenta).

That means lot of people using Arduino, making hardware and software, writing blogs, answering questions. That's the biggest plus of Arduino.


Add string inputs into an array I have been working on this a while and I cannot seem to figure it out. Essentially, I am using the app/server Blynk and their Terminal Widget to sent String inputs to my Arduino board. My code is below:

  String INFO;
  String fromTerminal = param.asStr();
  int indexstart = fromTerminal.indexOf(",");
  int indexend = fromTerminal.lastIndexOf(",");
  int counter = indexstart - indexend;
  INFO[counter] = fromTerminal;

My thoughts on the code was, based on the number of "," I enter in the string then that will assign my input to an index within the INFO array. However as I have tried several different things, I constantly get errors such as:
cannot convert 'String' to 'char' in assignment.
Oddly enough if I set: INFO[counter] = fromTerminal.toInt();
I dont get an error but I dont think that will allow me to print out my actual input. Any help is much appreciated, thanks!

I think you should better read about the String Object and don't mix this up with string as char array.


How to convert read characters to strings? How can I append a string e.g. "AA 00 01 00 FF FF A2" to serial data using Arduino?

The following code does not seem to be correct:

String comdata;
void loop() {
  while (Serial2.available() > 0) {
    c = Serial2.read();
    //c is "AA 00 01 00 FF FF A2"
    comdata +=c;
  }
  if(comdata.length()>0){
    Serial.println(comdata);
    //YES on HEX mode ;print "AA 00 01 00 FF FF A2"
    }
    delay(1000);
}

If I correctly understand your question, then please try following code:

uint8_t str[64];
uint8_t chrCtr = 0;
uint16_t twoChr;
boolean isSecondChr = false;

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

void loop()
{
  uint8_t chr;
  while (Serial.available())
  {
    chr = Serial.read();
    if ('a' <= chr && chr <='f')
    {
      chr &= 0x5F; // make it uppercase
    }
    if ('0' <= chr && chr <= '9' || 'A' <= chr && chr <= 'F')
    {
      if (!isSecondChr)
      {
        twoChr = chr << 8;
        isSecondChr = true;
      }
      else
      {
        twoChr |= chr;
        isSecondChr = false;
        str[chrCtr++] = hexToAscii(twoChr);
        if (chrCtr == 63)
        {
          str[chrCtr] = 0; // A string always terminated by zero
          Serial.println((char *)str);
          chrCtr = 0;
        }
      }
    }
    else if (chr == '#') // input terminated
    {
      str[chrCtr] = 0; // A string always terminated by zero
      Serial.println((char *)str);
      chrCtr = 0;
    }
    else
    {
      isSecondChr = false;
      // other character will be dropped
    }
  }
}

uint8_t hexToAscii(uint16_t hexWord)
{
  return (hexToBin(highByte(hexWord)) << 4) + hexToBin(lowByte(hexWord));
}

uint8_t hexToBin(uint8_t hexByte)
{
  return hexByte <= '9' ? hexByte - 48 : hexByte - 55;
}


Ensuring specific frequency at specific time? I, at the moment am trying to come up with a simple way where I can program an Arduino to provide a step signal with a given frequency, at a specific time.

The frequency has to be ramped up, and within a time duration of 10 seconds shall the frequency go from 0 Hz to 48000 Hz.

How do I ensure both the specific time of when the frequency occurs, and the specific frequency of the step signal?

Signal has to be used to driver a stepper motor.

Edit: Code current:

So i currently wrote this piece of code:

int timestep = 1;
while(1)
{
  unsigned long startTime = millis()
  while(startTime != 500)
  {
    digitalWrite(step_pin,LOW);
    delayMicroseconds(208/timestep);
    digitalWrite(step_pin,HIGH);
    delayMicroseconds(208/timestep);
  }

  timestep++;
}

For each 0.5s should the frequency be doubled..  would this work?

Edit 2.0:

I made an new implementation using @EdgarBonet 's answer, and with the help of Timer1 library that arduino provide (I guess?).

.h file

#ifndef stepper_motor_h
#define stepper_motor_h

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

#define step_pin  13
#define dir_pin   12
#define en_pin    11
#define max_step  200

 class stepper_motor
{
  public:
    stepper_motor();
    void step_pwm();
    static void callback();
    TimerOne timer1;
  private:
    //uint32_t period;
    bool alive_bool;
    //int step_count;
    bool position_bool;
};

#endif

.cpp file

#include "stepper_motor.h"

int step_count = 0;
uint32_t period = 40825UL << 16; // 20412,5 us fixed point arithmetic time = 0

stepper_motor::stepper_motor()
{
  //pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin, OUTPUT);
  pinMode(dir_pin, OUTPUT);
  pinMode(en_pin, OUTPUT);
  alive_bool = true;
  position_bool = false;
  step_count = 0;

}

static void stepper_motor::callback()
{
  if (step_count < 240)
  {
    uint32_t new_period = sqrt(2 * step_count / 4.8);
    period -= new_period;
    step_count++;
  }
  else
  {
    return;
  }
}

void stepper_motor::step_pwm()
{

  digitalWrite(en_pin, HIGH);

  delay(0.005);

  digitalWrite(dir_pin, HIGH);
  //LOW  - Move towards the sensor
  //HIGH -  Move away from the sensor

  delay(0.005);

  timer1.initialize(period);
  timer1.attachInterrupt(callback);
  timer1.pwm(step_pin, 512);

}

Generating a linear frequency ramp with accurate timings is not an easy
task. I am providing here only a partial answer, where I first go
through the math of the problem, then give some ideas for the
implementation.

The math

We are dealing with a frequency-modulated signal, with the frequency
ramping linearly from f = 0 at t = 0 up to a
maximum f = fM at
t = tM. Specifically, we have
fM = 48 kHz and
tM = 10 s.
Then, the instantaneous frequency is

f(t) = a t

where a = fM/tM = 4.8
kHz/s is the “acceleration” of the pulsed signal.

Let's define the “integrated frequency” as

n(t) = ∫ f(t) dt = a t²/2

This quantity can be interpreted as the number of cycles completed at
time t, except that it is a continuous variable. The first cycle
starts when n = 0 and ends when n = 1, the next
cycle starts when n = 1 and ends when n = 2, and
so on. The output signal would be high when the fractional part of n
is between 0.25 and 0.75 (or maybe between 0 and 0.5, depending on your
choice of initial phase).

From here, we can calculate at what time each cycle should start:

t(n) = √(2 n/a)

and, by successive differences, the length of each cycle:

n       0     1       2       3      ... 239,998    239,999    240,000
t       0     20,412  28,868  35,355 ... 9,999,958  9,999,979  10,000,000
length   20,412   8,455   6,488      ...        20.833     20.833
diff          -11,957 -1,967  -1,018 ...            -0.000043
approx        +81,650 -1,408  -913   ...            -0.000043

In the table above, all times are in microseconds. The lines are:

t: time
length: length of one cycle
diff: difference between lengths of successive cycles
approx: approximated formula for that difference

The columns are staggered because each cycles spans the duration between
two successive values of t, and duration differences are computed
between successive cycles. The approximated formula is based on the
Taylor expansion:

T(n+1) − T(n) ≈ dT/dn + 1/2 d²T/dn² = −aT³(1 − 3/2 aT²)

where T = 1/f, the instantaneous period, approximates the
length of one cycle. The approximation is not good for the very first
cycles, but it converges pretty fast to the correct value.

Implementation

I did not write an implementation, so I am giving here only some ideas
on how to do it.

I would use Timer 1 of the Arduino Uno, in one of the modes that allows
frequency-modulation, i.e. a PWM mode where the counter TOP is set by a
register (mode 8, 9, 10, 11, 14 or 15). I would set the prescaler to 8
in order to allow for the maximum required period length. The period
resolution would then be:

8 CPU cycles = 0.5 µs in modes 14 or 15 (fast PWM)
16 CPU cyels = 1 µs in the other modes

It could be noted that single-cycle resolution is possible with the
prescaler set to 1, but the first 5 cycles are too long for this
setting. Maybe the prescaler could be changed after the fifth cycle, but
it would be tricky to do so without any glitch.

The timer overflow interrupt would fire at the end of each cycle, and
it's ISR (namely TIMER1_OVF_vect) would be responsible for updating
the timer period in order to make the next cycle shorter than the one
just elapsed. It would do something like

period -= delta(period);

The period should be computed with 32-bit arithmetic, because the
changes get tiny by the end of the ramp. Only the 16 most
significant bits of the computed period would actually be written to the
timer register. The delta() function should be inlined and fast. I may
try the approximation from the previous section implemented in
fixed-point. Or maybe just a table lookup using only the most
significant bits of the period as an index, with the table in PROGMEM.

For details on how to actually program the timer, see
the datasheet of the ATmega328P, section 16.

Update: The following algorithm seems to work well. At least in
simulation, I did not put it inside an ISR. It assumes fast PWM, i.e. a
0.5 µs timer resolution. It remembers the current value of delta
and divides it by 2 each time the period falls below some threshold. The
computed f(t) is almost as smooth as you can expect given the
limited resolution of the timer.

uint32_t period = 40825UL << 16;  // 1st cycle is 20412.5 us
void update_period()  // should be in ISR(TIMER1_OVF_vect)
{
    static const uint16_t thresholds[] = {
            17633, 13309, 10229, 7954, 6230, 4905, 3873, 3063,
            2426, 1923, 1525, 1211, 960, 762, 605, 480, 381,
            302, 240, 190, 151, 120, 95, 76, 60, 48};
    static uint16_t threshold = 29000;
    static uint8_t index = 0;
    static uint32_t delta = 6UL << 27;

    uint16_t period_h = period >> 16;
    if (period_h <= 42) return;  // final frequency achieved
    if (period_h < threshold) {
        threshold = thresholds[index++];
        delta >>= 1;
    }
    period -= delta;
    // set the timer period register to (period >> 16) - 1.
}


How to write data in RAM memory using Arduino Uno or Arduino Due? I know that it is possible to write data in ROM(Read Only Memory).
But what about if I want to write data in RAM(Random Access Memory)?
Can I do it using "Arduino Uno R3"?
RAM is normally associated with volatile types of memory.

There are several examples about writing data in EEPROM as in a (Read Only Memory) which may have 8 pins.
In order to store values read from analog input 0 into the EEPROM we need to use the "EEPROM.write()" function.
These values will stay in the EEPROM when the board is turned off and may be retrieved later by another sketch.
ROM is a Non-volatile type memory.
SD card is also Non-volatile type of memory.
We know that there are few SD card shields for "Arduino Uno" and it is possible create your own shields.

But what about volatile types of memory?
what about if I want to write data in RAM like a "DDR SDRAM" or in a DDR3 memory which may have 240 pins instead of 8 pins?
So my question is is it possible to write data in "DDR SDRAM" using "Arduiono Uno R3"?
How? Where should I connect those 240 pins?

DRAM of any kind requires a memory controller which is not present in any AVR device. Larger AVR devices such as the ATmega64A and ATmega128A do have an external memory bus that can be used for SRAM and MMIO.


FTDI Breakout with additional ISP connector TL;DR - Can the six yellow ISP pins be used as a normal ISP?

The usual USB-TTL FTDI breakout board looks like this:

Recently, I came across a variant of the board shown below. However, what are the additional yellow header pins on this board for? They are labelled ISP.

Here is a view of the rear:

So can they really be used as a standard ISP/ICSP?

However, according to the diagram below, which labels the 6 pins in question, I am not sure that there is a valid correlation of signal lines.

That is to say, would CTS to MISO, RI to RST, DSR to SCK and DCD to MOSI work? Or is that why a special version of avrdude is required, as alluded to in FT232RL: USB to Serial 232 TTL Adapter –?and ISP? - post #6:

As a new feature there is a 6-pin ISP header available. With it, avrdude and avrftdi you can program Atmels and Arduino bootloaders. A special version of avrdude with compiled FTDI driver is neccessary.

However the provided link to that version of avrdude, with the compiled FTDI driver, is dead.
It is also said, in post #7, that these pins are actually equivalent to an X3 connector, as found on the older Arduino Dicimila/NG/Duemilanove boards.

and those can (evidently) be used like so, as a bit banged SPI,

It should be noted that the RI, CTS, DCD and DSR (labelled RSD) pins are available, along the sides of the original FTDI breakout board. So, does the breakout board with the ISP header just provide access to these same signals using a different header?
I am a little confused - have I just over thought this, and this breakout board is simply an ISP/ICSP header and an FTDI connector rolled into one board (when used with the appropriate version of avrdude)? Or is it not a usual ISP header? I can not find any specific documentation relating to this type of breakout board, as stated in post #4.
Can anyone say, definitively, what these six pins are for? If they are not a normal ISP header, could you provide a detailed way of using it? A schematic would be helpful.

There's a thread about that on the Arduino Forum - someone had a similar question.

I found a schematic (below) which is not for that board, however the header pins are labelled the same as you found, so it is plausibly similar.

It appears that header is used for "Synchronous Bit Bang mode" as documented here: Bit Bang Modes For The FT232R and FT245R (Application Note AN_232R-01, Document Reference No.: FT_000339)

You can in fact configure that header to be an SPI programmer, as described for example, in FT232R Bitbang Programmer.

I made up a test as I had a similar board in my parts drawer:

It had provision for a 6-pin header similar to yours. Turning the board over we can see that they were labelled exactly the same as yours:

I soldered on a header (in yellow, to be consistent) giving me this:

I added a white dot to indicate pin 1 (visible on the edge) so I plug the cable in the right way around.

When I attempted to use the board I got this message from avrdude:

  avrdude: error: no libftdi or libusb support. Install libftdi1/libusb-1.0 or libftdi/libusb and run configure/make again

So, it had to be compiled from scratch! I am using Ubuntu 14.04 if you are trying to follow along. :)

Download avrdude

Go to the site http://www.nongnu.org/avrdude/

I downloaded version 6.3 source: http://download.savannah.gnu.org/releases/avrdude/avrdude-6.3.tar.gz

Install libusb and libftdi

Before compiling I had to grab libusb and libftdi:

sudo apt-get install libusb-1.0-0-dev
sudo apt-get install libftdi-dev

Compile avrdude

Now we make avrdude after extracting the archive and navigating to its folder:

./configure --enable-libusb --enable-libftdi
make

Find correct configuration

Inside the avrdude.conf file which comes with avrdude I found (after some pondering) this seems to be the correct entry:

# see http://www.geocities.jp/arduino_diecimila/bootloader/index_en.html
# Note: pins are numbered from 1!
programmer
  id    = "arduino-ft232r";
  desc  = "Arduino: FT232R connected to ISP";
  type  = "ftdi_syncbb";
  connection_type = usb;
  miso  = 3;  # CTS X3(1)
  sck   = 5;  # DSR X3(2)
  mosi  = 6;  # DCD X3(3)
  reset = 7;  # RI  X3(4)
;

The mapping of pins to numbers works like this... From the PDF about bit bang mode mentioned above we have this table, with annotations in blue by me:

The numbers refer to the bit number (i.e. in the range 0 to 7) in the "bit banged" data byte. We can see from the earlier schematic that, for example, MISO on the ICSP header is wired to CTS on the FT232RL. Thus MISO is data bit 3, which we tell avrdude in the above configuration. Similarly SCK is data bit 5, and so on.

I attempted to test like this:

./avrdude -C avrdude.conf -carduino-ft232r -pm328p  -v

Fix permissions

I got a permissions error which was fixed by creating a file in the folder /etc/udev/rules.d/ called 71-FTDI.rules. Inside this is:

SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE:="0666"

The numbers may vary for your board. You need to find the vendor and product ID. In Ubuntu you can do lsusb and see (amongst other things):

Bus 003 Device 061: ID 0403:6001 Future Technology Devices International, Ltd FT232 Serial (UART) IC
                       ^^^^ ^^^^

Note the two hex numbers, which get copied into the rules file.

After doing that, tell the system to reload the rules:

sudo udevadm control --reload-rules

Then unplug and replug the FTDI board to get it to notice the new permissions.

Test board detection

Finally, the avrdude line above works and reads the chip:

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as FD

avrdude: safemode: hfuse reads as DE
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:DE, L:FF)

avrdude done.  Thank you.

I had mine plugged into an ATmega328P.

Example connected to a Diavolino

Once we have got this far you just connect the FTDI board to your target board with a straight-through cable.

Summary

The FTDI board you have (and the one I have) can be used as a ICSP programmer for the AVR chips, as described above. Thus a simple board can be both a USB to serial converter, and also an ICSP programmer.

I see similar boards selling on eBay for around $5 so that is probably quite a cheap programming option.


Is there a way to keep a program on the Arduino after uploading new sketches? I am looking for a way to keep a program on my Arduino Nano 3.0, after uploading new sketches on it. I would like to have a program on it that will control th screen and buttons at it. The user will choose one of the programs displayed on the screen and execute/pause/stop them. These programs will be uploaded on the Arduino, while the previous programmes stay.

If you are familliar with the Lego Mindsdorm microcontroller, you probably know waht I am looking for.

Is there a way to do that.

I'm not familiar with Lego Mindstorm, but I think I understand what you want and I am certain there is a way to do it, but I don't think it will be easy or even practical and I can't tell you exactly how to do it.

I'm pretty certain there will be a way to load a 'module' into memory and then make the program call that address.  I haven't got a clue how you would do it though, sorry.  GCC doesn't have a concept of DLLs like window does, but it does have shared libraries.  Or you might look at just reading a block of memory in.

Other approaches might be to have all the 'programs' as functions within you main program and call them depending on the user's input.  You can only do this if the 'programs' are small enough.

If you can refactor your 'programs' to extract the common code into functions and then have a data file (which could be read at runtime) that called the functions for each of your programming.  Basically  invent your own higher level programming language.  This wouldn't work if your code was very different and you could factor it down to a small enough number of functions.

Would it be possible to just have a number of hex files (compiled programs?) all of which have the common screen/button handler in and then have the special code for the appropriate program.  These could all be stored on an SD card and then loaded into memory by a second Arduino (sounds plausible to me, I'm sure someone will tell me whats wrong with that idea.)

An alternative based on the inverse of the above solution would be to have one Arduino to control the screen/buttons and it programs a second Arduino with the specialist code that is connected to the rest of your kit.


one Arduino with RS485 and Ethernet shields: does this work? I'm planning to wire a few Arduinos together via RS485, and have one of them act as a hub that collects information from the others and presents it via http on an Ethernet connection.

For instance an Aduino MKR with ETH shield and 485 shield. Can I expect these to work together? My worry is having 2 shields that potentially need lots of bandwidth, timing issues etc.

Should be no problem.

The ETH shield uses SPI to communicate with a W5500 chip. That chip does most of the network processing for you.

The 485 shield just connects to the UART TX and RX pins. It's just serial communications with a couple of control pins from there on out.

Neither use any pins that the other one uses.


Connecting ethernet shield to computer What configuration settings do I need to change on my computer to use the ethernet shield mounted on my Arduino UNO as I don't want to connect the ethernet shield to the router?

First off you need a basic understanding of TCP/IP networking. One you have that you need to:

Allocate yourself a new subnet - one that's not your normal local network (say 192.168.1.0/24)
Assign an IP in that subnet to your Arduino (say 192.168.1.1)
Assign a different IP in that subnet to your PC (say 192.168.1.2)
Configure your Arduino's sketch with it's IP address and netmask
Configure the PC's Ethernet interface with it's IP address and netmask
Connect the two together with a suitable cable.  If the PC's Ethernet port doesn't have auto-direction sensing you will require a special cross-over cable where TX+/TX- and RX+/RX- are swapped over.


Turn on LEDS one after another I am trying to turn on LEDs one after the other so that I can start at one end and slowly turn the LEDs until it reaches the middle of the strip. The code works coming from the end of the LED strip, but not when coming from the start of the strip. From the start of the strip, it just turns on all the LEDs up until the midpoint.

int midpoint = 30;
int R = 255;
int G = 0;
int B = 0;
for(int j = 0; j<midpoint; j++){
     //starting from the end, filling towards the middle
        for(int k = NUM_LEDS-j; k < NUM_LEDS; k++){
           leds[k] = CRGB (R, G, B);
        }
//there's some other code here in the interim
FastLED.show();
delay(20);
     //starting from the beginning, filling towards the middle
     //this is the section of code that doesn't work correctly
        for(int l = j - 1; l < midpoint; l++){
           leds[l] = CRGB (R, G, B);
           }
//more interim code
FastLED.show();
delay(20);
}

Okay so i figured it out. The problem is that the for loop is starting at 0 and counting all the way up to the midpoint. What I wanted is for it to light all the LEDs that are at j and below. So I changed it to iterate down instead of up. Here's the new loop:

for(int l = j; l < midpoint & l > -1; l--){
   leds[l] = CRGB (R, G, B);
}

The extra qualifier l > -1 is to make sure that it doesn't try to go below leds[0]


How can I connect an Arduino / ESP8266 to an Azure MySQL database? I am currently trying to connect an ESP8266 to my Azure MySQL database via WiFi, but have not yet been successful.

I have tried a bunch of guides, but no luck and I'm running out of ideas. I have made a connection to an IoT Hub in Azure but could not forward the messages to the MySQL database in the cloud. I managed to get it stored in a blob datatype but had so many issues with it that I kinda scratched that idea.

Last thing I tried was trying to implement the example from
https://github.com/ChuckBell/MySQL_Connector_Arduino
more specifically the 'connect_wifi' example. I was unable to find the ip of my azure server so i tried using some of the code from the 'connect_by_hostname' but no luck there.

I'm new to Arduino and cloud in general so any help is appreciated.

Not sure how you would directly connect with an C++ embedded file. One way you could achieve this is by creating a computer application and connect to the machine via Bluetooth.

{Arduino}
* Intake information
* Process into commands
* Push through software serial ----(Blue Tooth-----> { PC or MAC}
                                                    *Create C# or Swift App
                                                    *Intake information via COM-PORT
                                                    *Prepare SQL command with serial data
                                                    *Push to database server

This may of not of been the method you were looking for, but it's a way I found around the issue when working with Azure Databases and Arduino Micro-Controllers. An alternative is going to Raspberry Pi which has a little more resources to deal with server functions.

Hope this helps.


Is my HC-SR04 sensor broken? I am extremely new to Arduino and electrical engineering, and the project I am attempting involves a ultrasonic sensor.  I am using the HC-SR04 with the Elegoo Mega2560 Arduino board.  A few days ago I was able to print out the distance correctly with an Arduino library, but after adding a h-bridge, 2 motors, and 2 9-volt batteries, the sensor didn't seem to work properly.  I went back to a simple circuit with only the HC-SR04, and the distance readouts were all over the place.  No matter what, the distance stayed between 90 and 120, mainly staying in the 110s.  These numbers seemed to have no correlation with the actual distance.  I even tried to calculate the distance myself in case there was something wrong with the library.

I have the VCC pin on the HC-SR04 connected to the 5v on the Arduino, the GND pin connected to the GND pin on the Arduino, the Trigger pin connected to pin 50 on the Arduino, and the Echo pin on the Arduino connected to pin 52 on the Arduino.  The Arduino is connected to my computer through USB.

Here is my sketch for printing out the distance without a library:

const int triggerPIN = 50;  //these are digital pins on the Arduino board
const int echoPIN = 52;     //I'm sure these pins aren't broken because I never used them before now

long duration;
int distance;

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

    pinMode (triggerPIN, OUTPUT);
    pinMode (echoPIN, INPUT);

    delay(1000);
}

int getDistance () {
    digitalWrite (triggerPIN, LOW);
    delayMicroseconds (2);

    digitalWrite (triggerPIN, HIGH);
    delayMicroseconds (10);
    digitalWrite (triggerPIN, LOW);

    duration = pulseIn (echoPIN, HIGH);
    distance = duration * 0.034 / 2;

    Serial.println (distance);
}

void loop() {
    getDistance ();  //I tried putting the code directly in the loop function with the same result
}

I am afraid that I broke either a part of the Arduino board or the sensor when I was fiddling around with the two batteries.  Is it possible to break a HCSR04 sensor by connecting two much voltage to the VCC pin on the sensor?  If so, how should I prevent this in the future?  I know that the working voltage for a HCSR04 is 5V, does this mean it needs at least 5V or no more than 5V?  I wanted to know for sure that it was broken and not an error on my part before I bought a new one.    Thanks in advance!

A major functional difference between the code in your question and the usual ping sensor example is that your code repetitively measures as fast as it or the output stream will allow.

In contrast, the normal example has a delay(100) after each measurement cycle.  This allows 1/10th of a second time for any longer room echoes to die out, and thus avoid confusing new measurements.

While that might not be your immediate or only problem, it is generally a good idea not to try to take sonar measurements so closely spaced in time that they could overlap.

Should your sketch also need to do other things, instead of a blocking delay() you can check the elapsed time and only take a new sonar measurement once a certain amount of time has passed; in the meantime your program can continue with any other critical operations.


Sim808 module HTTP Bad request I have an Arduino UNO and sim808 EVB-V3.02.4.
I want to send a GET request to my url but I always receive 400 Http bad request error.

#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PIN_TX    7
#define PIN_RX    8
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

char http_cmd[] = "GET /index.php?lat=10&long=100 HTTP/1.0\r\n\r\n";
char buffer[512];

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

void loop() {
  //*********** Attempt DHCP *******************
  while(!sim808.join(F("cmnet"))) {
      Serial.println("Sim808 join network error");
      delay(2000);
  }

  //************ Successful DHCP ****************
  Serial.print("IP Address is ");
  Serial.println(sim808.getIPAddress());

  //*********** Establish a TCP connection ************
  while(!sim808.connect(TCP,"39c309ae.ngrok.io", 80)) {
      Serial.println("Connect error");
  }
  Serial.println("Connection success");

  //*********** Send a GET request *****************
  Serial.println("waiting to fetch...");
  sim808.send(http_cmd, sizeof(http_cmd)-1);
  while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0){
          Serial.println("fetch over...");
          break;
      }
      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
  }

  //************* Close TCP or UDP connections **********
  sim808.close();

  //*** Disconnect wireless connection, Close Moving Scene *******
  sim808.disconnect();
  delay(5000);
  }

My php code:

<?php
file_put_contents('test.txt', $_GET['lat'] . '---' . $_GET['lon']);
print '
<html>
<head>
<title>Good</title>
</head>
<body>
Was Good
</body>
</html>
';
?>

I want just open http://39c309ae.ngrok.io/index.php?lat=10&long=100 with arduino and sim808.

What is wrong in my codes?

You aren't sending the Host: header with your request.  Without that the web server has no idea which website you want to get the /index.php page from.

char http_cmd[] = "GET /index.php?lat=10&long=100 HTTP/1.0\r\n"
                  "Host: 39c309ae.ngrok.io\r\n"
                  "\r\n";


Light up more than one LED connected to 74HC595 Shift Register I have a 74HC595 Shift Register with a LED (and resistor) on each of the 8 output pins.
I can light them all up
I can light one up

How do I light two up?
For example the one on pin 2 and the one on pin 7

I used this a my starting point.
https://learn.adafruit.com/adafruit-arduino-lesson-5-the-serial-monitor?view=all

Is 74HC595 Shift Register  the correct componet to use?

You don't mention if you are using and Arduino, but I will assume that is the case.

Using the shift register to light up LEDs is fairly straight forward.

You can use the ShiftOut() function to send out an 8bit binary value to the register. https://www.arduino.cc/en/Reference/ShiftOut

In summary however, if you want to light up the LEDs on the output pins 2 and 7 you would shift out b01000010 to the shift register. If you wanted pins 4, 5 and 7 to light up, you shift out b01011000. These assume the least significant bit is sent first.

Here's an example:

// set shift register output pins 2 and 7 to high
uint8_t data = 1<<2 | 1<<7; // use bit shifting

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, data); // send the data
digitalWrite(latchPin, HIGH);


ArduinoUno+LcdKeypad+ArduinoWifi=Pins Problems Is it possible to connect these two shields to my Arduino Uno? After a research on the internet, I discovered that they use some of the same pins. Even so, is it still possible for me to connect the LcdKeypad and the ArduinoWifi on my Arduino Uno? (the LCD would be on top)

Here are the pic of the shields, and some information:

LDC KEYPAD

Arduino WIFI

WiFi shield info:

  The Arduino communicates with the processor WiFi shield with the microSD card by SPI
  (Eurotherm the ICSP bus) that is on pins 11, 12
  and 13 at Uno. The pin 10 is used to select the HDG104 and pin 4 to
  the microSD card(i dont need the pin 4 cause i wont use SD). These pins can not be used
  for input and output. The
  digital pin 7 is used for initialization of the communication protocol
  between the shield and Arduino WiFi and should not be used.

LCD info:

  This shield we will have to use the following sequence to initialize
  the library LiquidCrystal:
  LiquidCrystal lcd (8,9,4,5,6,7);

As you guys have noticed, there is the pin 7 on both shields that I need to use. How would it work? Can I do this? If i can't, is there any solution that I can expand my pins that would not result buying a Mega?

I still have to connect two INFRA-RED sensors and a motor (using pins 0, 1, and 2). I don't know if i can connect on the pins TX and RX (they seem to work).

So here are your needs:

WiFi, which uses pins 4, 10, 11, 12, 13. I know you said that you don't need pin 4 since no SD, but because that pin switches on/off the SD card, if you use it at all. Note: As Connor Wolf points out, it's not really relevant when there's no SD card. If you're facing problems with the Ethernet shield using the LCD additionally, you might have to reroute pin 4.
LCD, which uses pins 4, 5, 6, 7, 8, 9. The standard Arduino LCD library can use any pins, but your shield is hard wired to use those. As mentioned before, you can reroute them if you want to. Below is the method for rerouting pins.

Rerouting pin 7 (you need to do this!):

Bend pin 7 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
Use LiquidCrystal lcd(8,9,3,5,6,2); if you're rerouting pin 4, or LiquidCrystal lcd (8,9,4,5,6,2); in your code if you're not rerouting
Attach a jumper between the pin 7 on the header of the WiFi shield and the pin 7 on the Arduino Uno
Attach a jumper between the pin 2 of the WiFi shield (or the Uno, if that's easier) and the pin 7 of the LCD using the free space of the pin bent above it.

This will isolate pin 7 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 2 on your Arduino to pin 7 on the LCD shield.

Rerouting pin 4 (optional):

Bend pin 4 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
Use LiquidCrystal lcd(8,9,3,5,6,2); in your code
Attach a jumper between the pin 4 on the header of the WiFi shield and the pin 4 on the Arduino Uno
Attach a jumper between the pin 3 of the WiFi shield (or the Uno, if that's easier) and the pin 4 of the LCD using the free space of the pin bent above it.

This will isolate pin 4 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 3 on your Arduino to pin 4 on the LCD shield.

For number of pins, you should be fine. You can use pins 0 and 1 (TX/RX) as long as you aren't connecting to the computer or any other UART device  (i.e. using the Serial() library). Don't forget you can use the analog pins as digital pins by referencing them as A0 to A5.


shiftOut using SPI isn't working I made a sample using two of them using Arduino UNO.
So I did that like this:

(There aren't any resistor on that image, but there are 220ohm resistor on every LEDs.)
And uploaded this code.

//1.6us+62.5ns
#include <SPI.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))

int latchPin = 12;
int clockPin = 13;
int dataPin = 11;

byte data[]={ 0b10101010,0b11001100 };

void _595_out() {
    cbi(PORTB, 4);
    SPI.transfer(data[0] );
    SPI.transfer( data[1] );
    sbi(PORTB, 4);
}

void setup() {
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.begin();
}

void loop() {
    _595_out();
}

And this worked as I expected. But, when I changed sketch like this,

//1.6us+62.5ns
#include <SPI.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))
#define CHIPNO 2
int latchPin = 12;
int clockPin = 13;
int dataPin = 11;

byte data[]={ 0b10101010,0b11001100 };

void _595_out() {
    cbi(PORTB, 4);
    SPI.transfer(data[0]);
    SPI.transfer(data[1]);
    sbi(PORTB, 4);
}

void setup() {
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.begin();
    Serial.begin(9600);
}

void loop() {
    for(unsigned int z = 0; z < 65535; z++) {
        data[0] = z & 255;
        data[1] = (z & 65280) >> 8;
        Serial.println("A");
        Serial.print(data[0]);
        Serial.print("/");
        Serial.println(data[1]);
        Serial.println("B");
        _595_out();
        Serial.println("C");
        delay(500);
    }
}

74HC595s aren't working. Any LEDs aren't on.
Printing Serial works well. Only 74HC595s aren't working.
And Removing all Serial-related thing doesn't solved this problem.
Where did I do wrong?

int latchPin = 12;

You use pin 12 as the latch pin. Once you activate SPI the hardware takes over control of the pins MOSI, MISO and SCK. Pin 12 is MISO and thus attempting to change it in your code will have no effect.

You should use some other pin as the latch pin (pin 10 is often used).

  And shiftOut using SPI is working when I use first code

shiftOut is a software-based method of clocking out bits. It doesn't use hardware and thus it doesn't take control of pin 12.

Note: Answered originally on the Arduino Forum


Connecting Arduino To mains How would iconnect my Arduino Mega to house Mains, without buying a transformer, and having to make a whole setup for that.  Can i just use a regular phone adapter?  Or is 1 Amp too large (or 2 Amps).

Amps tell you how much current you can draw from the power supply, or "how much it can do".

You can hook up 3Amps power supply to a device that draws 1Amp and it will work ok, still having 2 amps of reserve.

You must pay attention to power supply voltage and keep it in specified range.

Arduino Mega has recommended input voltage of 7-12V, so you must deliver at least 7V. There are plenty of cheap wall power supplies with voltage regulation from 1.5V to 12V.

How much current it will draw depends on your application, but I doubt that you can suck more than 0,5-1A in a typical application.


DHT11 returning incorrect values I am trying to use DHT11 sensor with Arduino. But unfortunately it is returning following values:

Temperature = 1.00
Humidity = 2.00

My code is as follows:

#include <dht.h>
dht DHT;
#define DHT11_PIN 7

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

void loop()
{
    int chk = DHT.read11(DHT11_PIN);
    Serial.print("Temperature = ");
    Serial.println(DHT.temperature);
    Serial.print("Humidity = ");
    Serial.println(DHT.humidity);
    delay(1000);
}

Link to the library I am using is here

I have connected +ve to 3.3 V
I have connected -ve to Ground
I have connected out to digital pin # 7

You have to call the functions:

#include <DHT.h>
#define DHT11_PIN 7
DHT dht(DHT11_PIN, DHT11);

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

void loop() {

    float humidity = dht.readHumidity();
    float temperature = dht.readTemperature();

   if (isnan(humidity) || isnan(temperature)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

    Serial.print("Temperature = ");
    Serial.println(temperature);
    Serial.print("Humidity = ");
    Serial.println(humidity);

    delay(1000);
}

Edit


2 Channel Relay normal open is not working with NodeMCU but led on board light up I am pretty new to NodeMCU (ESP8266) and Arduino IDE in general. I followed various documentation / blogs to set up 2 Channel Relay with NodeMCU chip.

Below is sketch code for it.

#include<CayenneMQTTESP8266.h>
#define CAYENNE_DEBUG
#define CAYENNE_PRINT Serial

#define LEFT_GARAGE 4
#define RIGHT_GARAGE 5

char ssid[] = "XXXXXXXXXXXXXXXXXXXXXXXX";
char password[] = "XXXXXXXXXXXXXXXXXXXXXX";

char username[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
char mqtt_password[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
char client_id[] = ""XXXXXXXXXXXXXXXXXXXXXX";";

void setup() {
  Cayenne.begin(username, mqtt_password, client_id, ssid, password);
  pinMode(LEFT_GARAGE, OUTPUT);
  digitalWrite(LEFT_GARAGE, HIGH);
  pinMode(RIGHT_GARAGE, OUTPUT);
  digitalWrite(RIGHT_GARAGE, HIGH);
}

void loop() {
  Cayenne.loop();
}

// Left Garage Door
CAYENNE_IN(0){
  int currentValue = getValue.asInt();
  digitalWrite(LEFT_GARAGE,!currentValue);
}

//Right Garage Door
CAYENNE_IN(1){
  digitalWrite(RIGHT_GARAGE,!getValue.asInt());
}

On relay board I tried to connect wire in 2 different configuration.

1st Config:

vcc -> 3.3v from NodeMCU
in1 -> D1/GPIO 04 from NodeMCU
in2 -> D2/GPIO 5 from NodeMCU
GND -> GRD from NodeMCU

2nd Config:

vcc -> 5v USB from NodeMCU
in1 -> D1/GPIO 04 from NodeMCU
in2 -> D2/GPIO 5 from NodeMCU
GND -> GRD from NodeMCU

In 1st config, On relay board respective LED's are turning on when Cayenne buttons are pressed but when I check for continuity on multi meter I don't get anything.

In 2nd config, no LED and no continuity.

am I missing something here? Any feedback/comments are highly appreciated.

Your second configuration is right because from picture of relay module it clear that it requires 5V supply.

 relay working principal is:

when the signal port(in1/in2) is at low level, the signal light will light up and the optocoupler (it transforms electrical signals by light and can isolate input and output electrical signals) will conduct, and then the transistor will conduct, the relay coil will be electrified, and the normally open contact of the relay will be closed.
When the signal port(in1/in2) is at high level, the normally closed contact of the relay will be closed. So you can connect and disconnect the load by controlling the level of the control signal port.

As you mentioned that in second configuration there is no LED glow. For find out solution of your problem, you have do one test. Test voltage level of D1/D2. Just make connection on breadboard as mentioned in image.

If voltage level is correct that it might be problem with your relay module.

Also I have attached here relay connection reference for your directness.


Reducing lag between the arduino and a processing sketch on my computer I'm currently on project #14 of the Arduino project book.

I'm trying to control a processing sketch on my laptop using my Arduino. This is accomplished by using a potentiometer to control the background of an image.

Arduino code:

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

void loop(){
  Serial.write(analogRead(A0)/4);
}

Processing:

//imports serial library
import processing.serial.*;
//setups the serial object
Serial myPort;
//creates an object for the image
PImage logo;
//variable to store background color
int bgcolor = 0;

void setup(){
  colorMode(HSB,255);
  logo = loadImage("http://arduino.cc/logo.png");
  size(logo.width,logo.height);
  println("Available serial ports");
  println(Serial.list());
  myPort = new Serial(this,Serial.list()[0],9600);
}
//equivalent of arduino's loop function
void draw(){
  if(myPort.available() > 0)
  {
    bgcolor = myPort.read();
    println(bgcolor);
  }

  background(bgcolor,255,255);
  image(logo,0,0);
}

Now, while the code works, and the background color changes as i turn the potentiometer, there is a huge lag between turning the potentiometer and seeing the background change color, and the values from the Arduino/potentiometer change on the processing's serial monitor.

What I've tried:

Changing the speed of Serial communication

I've noticed that when I decrease the speed of Serial communication, e.g. around 100, the delay between turning the potentiometer and seeing it change on my laptop decreases to about 1 second. However, when I decrease the speed of Serial communication even further, e.g. a value of 1, the delay increases again.

On the flip side, at the standard speed of 9600, the delay is huge, roughly 5sec ++ before the changes in the potentiometer show up on the laptop/processing.

Why does decreasing the communication speed (up to a certain point) decrease the time lag, and increasing it increase the time lag? Also, is there anyway I can make it near instantaneous?

As already pointed out, your Arduino is saying too much too fast. Adding delay() will slow it down, but still it keeps yelling at Processing. Ideally, you want Processing to ask for the value when it's convenient, and then receive one answer from your Arduino.

Enter SerialEvent().

As opposed to loop() on your Arduino and draw() in Processing, everything inside serialEvent() only excutes when there is something new in the serial buffer. So instead of Processing asking questions as fast as possible and your Arduino yelling back even faster, they can have a nice, polite (asynchronous) conversation.

Both Processing and Arduino have a serialEvent. This is serialEvent() on the Arduino and this is serialEvent() in Processing. Using serialEvent on both sides, this is what would happen:

Processing sends a character to the serial connection. This could be any character, but if we predetermine one we can filter out any unwanted requests caused by e.g. a noisy signal. For this example, let's send a V every time we want a new reading of your potmeter. After the character is sent, we continue our business as usual. Not waiting around for an answer here!
On the Arduino side nothing is happening, until it receives data in the serial buffer. It checks whether the incoming character is a V, and lucky us, it is. The Arduino reads the potmeter's value once, outputs that value to serial once, and goes back to chilling out, maxing relaxing all cool. Protip: terminate the value with a character (* in our case). This will help you in the next step.
Processing is doing its regular interfacey pixel business when all of a sudden there's a disturbance in the force new data in the serial buffer. It switches to serialEvent(), and starts reading the serial data, until our terminating * is encountered. Knowing for sure this was the last character worth reading, we can now store the incoming value in a variable that stores the Arduino's reading.
That's it. Processing now knows the new sensor value and carries on with whatever we tell it to do. Meanwhile, your Arduino is enjoying the weather or contemplating its existence until there is incoming serial data.


Get an additional analog pin? I have the following board:

As far as I can tell, there's only a single analog pin (A0). But I need at least 2 additional (for 3 total).

Is there some way to fake analog input on GPIO pins?

The ESP8266 only has one ADC pin. You can:

Use an analog MUX to switch that pin between different signals
Connect an external I2C ADC chip
Connect an external SPI ADC chip
Connect the ESP8266 to another MCU (such as an Arduino) and get that to do analog readings.


Can not receive data from Python code I want to send 4 float numbers from Python code to an Arduino; I was trying to send it via serial and I have some problems.
here is my Python code:
import time
import serial
import struct

data = serial.Serial('COM6', 9600, timeout=1)
time.sleep(1)

while True:
   a = str(47.256*1000)
   data.write(a.encode())

Here is my Arduino code :
String msg;

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

void loop()
{
  if (Serial.available()) {
    msg = Serial.readString();
  }

  if (msg.toInt()>30){
    digitalWrite(13, 1);
  }
}

end of code
Thanks in advance.
My problem is that it does not work (LED does not turn on while I send data from the Python code in a while loop; when I remove the while and make it send data 1 time it works (LED turns on). Any ideas why this could be happening?

It would be easier if you used Arduino <--> Python compatible libraries to ensure the communication between the two is robust and reliable. An example of such libraries would be pySerialTransfer and SerialTransfer.h.

pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.

Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs.

Example Python Script:

import time
from pySerialTransfer import pySerialTransfer as txfer

if __name__ == '__main__':
    try:
        link = txfer.SerialTransfer('COM17')

        link.open()
        time.sleep(2) # allow some time for the Arduino to completely reset

        while True:
            send_size = 0

            ###################################################################
            # Send a list
            ###################################################################
            list_ = [1, 3]
            list_size = link.tx_obj(list_)
            send_size += list_size

            ###################################################################
            # Send a string
            ###################################################################
            str_ = 'hello'
            str_size = link.tx_obj(str_, send_size) - send_size
            send_size += str_size

            ###################################################################
            # Send a float
            ###################################################################
            float_ = 5.234
            float_size = link.tx_obj(float_, send_size) - send_size
            send_size += float_size

            ###################################################################
            # Transmit all the data to send in a single packet
            ###################################################################
            link.send(send_size)

            ###################################################################
            # Wait for a response and report any errors while receiving packets
            ###################################################################
            while not link.available():
                if link.status < 0:
                    if link.status == -1:
                        print('ERROR: CRC_ERROR')
                    elif link.status == -2:
                        print('ERROR: PAYLOAD_ERROR')
                    elif link.status == -3:
                        print('ERROR: STOP_BYTE_ERROR')

            ###################################################################
            # Parse response list
            ###################################################################
            rec_list_  = link.rx_obj(obj_type=type(list_),
                                     obj_byte_size=list_size,
                                     list_format='i')

            ###################################################################
            # Parse response string
            ###################################################################
            rec_str_   = link.rx_obj(obj_type=type(str_),
                                     obj_byte_size=str_size,
                                     start_pos=list_size)

            ###################################################################
            # Parse response float
            ###################################################################
            rec_float_ = link.rx_obj(obj_type=type(float_),
                                     obj_byte_size=float_size,
                                     start_pos=(list_size + str_size))

            ###################################################################
            # Display the received data
            ###################################################################
            print('SENT: {} {} {}'.format(list_, str_, float_))
            print('RCVD: {} {} {}'.format(rec_list_, rec_str_, rec_float_))
            print(' ')

    except KeyboardInterrupt:
        link.close()

    except:
        import traceback
        traceback.print_exc()

        link.close()

Example Arduino Sketch:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

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

void loop()
{
  if(myTransfer.available())
  {
    // send all received data back to Python
    for(uint16_t i=0; i < myTransfer.bytesRead; i++)
      myTransfer.txBuff[i] = myTransfer.rxBuff[i];

    myTransfer.sendData(myTransfer.bytesRead);
  }
}

Note that you can send more than just individual chars with these libraries. It is possible to transfer floats, ints, bytes, arrays, and even structs (or any combination of the like) within your program using the libraries! See the examples in SerialTransfer.h for more info

For theory behind robust serial communication, check out the tutorials Serial Input Basics and Serial Input Advanced.


How to use ESP8266 wifi shield as a hotspot? I have bought a ESP8266 wifi shield and I want to use it hotspot, I have tried the examples that have been provided in Arduino IDE, and the shield is getting connected to my network and giving me a wifi but without internet access (like I can connect my phone to the shield but I cannot browse the internet).
Any suggestion please?

Thanks......

Connecting through the ESP8266 to the internet would require the ESP8266 to handle Network Address Traversal and/or routing, which is not officially supported.

However, if you are prepared to do a lot of work, it can be done. The performance and reliability is bad, but it can be done. See http://bbs.espressif.com/viewtopic.php?t=960 Note that this will require far more skills than running the examples in the Arduino IDE.


Delay function without using a timer Is there a delay function available that does not use millis() which itself makes use of a timer? Does not need to be hyper-exact.

delayMicroseconds(1000);// maximum delay is 65535 uS

or

#include <util/delay.h>
_delay_ms(1);


Sending data to serial port using Processing IDE (Debug works but run doesn't) I'm trying to read a series of numbers in a text file on my PC then send them to my Arduino board via serial port. The numbers are split by commas and dashes so I perform two loops. Sending a number to the serial port should light the equivalent LED on the Arduino board. The problem is that only the first iteration in the first loop doesn't light the equivalent LEDS in run mode though it does in the debug mode.; other iterations and other loops run flawlessly. There aren't any problems with the hardware 100% for sure. Any help would be greatly appreciated.
Here is the code:

import processing.serial.*;
import java.io.*;
int mySwitch=0;
int counter1=0;
int counter2=0;
String [] subtext;
String[] Lines;
Serial myPort;

void setup(){
//Create a switch that will control the frequency of text file reads.
//When mySwitch=1, the program is setup to read the text file.
//This is turned off when mySwitch = 0
 mySwitch=1;

 //Open the serial port for communication with the Arduino
 //Make sure the COM port is correct
 myPort = new Serial(this, "COM36", 9600);
 myPort.bufferUntil('\n');
}

void draw() {
 if (mySwitch>0){
 /*The readData function can be found later in the code.
 This is the call to read a CSV file on the computer hard-drive. */
 readData("Y:/MyTextFile.txt");

 /*The following switch prevents continuous reading of the text file, until
 we are ready to read the file again. */
 mySwitch=0;
 }
 /*Only send new data. This IF statement will allow new data to be sent to
 the arduino. */

  while(counter1<Lines.length){
 subtext = splitTokens(Lines[counter1],",");
 counter2=0;
 while(counter2<subtext.length){
 /* Write the next number to the Serial port and send it to the Arduino
 There will be a delay of half a second before the command is
 sent to turn the LED off : myPort.write('0'); */

 myPort.write(subtext[counter2]);

 //delay(300);

// delay(100);
 //Increment the counter so that the next number is sent to the arduino.

 counter2++;
 }
 delay(2000);
 myPort.write('0');
 delay(2000);
 counter1++;
 }
 //If the text file has run out of numbers, then read the text file again in       5 seconds.
delay(5000);
mySwitch=1;

}

/* The following function will read from a CSV or TXT file */
void readData(String myFileName){

 File file=new File(myFileName);
 BufferedReader br=null;

 try{
 br=new BufferedReader(new FileReader(file));
 String text=null;

 /* keep reading each line until you get to the end of the file */
while((text=br.readLine())!=null){
 /* Spilt each line up into bits and pieces using a comma as a separator */
 Lines = splitTokens(text,"-");
 }
 }catch(FileNotFoundException e){
 e.printStackTrace();
 }catch(IOException e){
 e.printStackTrace();
 }finally{
 try {
 if (br != null){
 br.close();
 }
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }

Here is the Arduino code:

void setup() {
 // initialize the digital pins as an output.
 pinMode(2, OUTPUT);
 pinMode(3, OUTPUT);
 pinMode(4, OUTPUT);
 pinMode(5, OUTPUT);
 pinMode(6, OUTPUT);

// Turn the Serial Protocol ON
 Serial.begin(9600);
}

void loop() {
 byte byteRead;

 /* check if data has been sent from the computer: */
 if (Serial.available()) {

 /* read the most recent byte */
 byteRead = Serial.read();
 //You have to subtract '0' from the read Byte to convert from text to a    number.
 byteRead=byteRead-'0';

 //Turn off all LEDs if the byte Read = 0
 if(byteRead==0){
 //Turn off all LEDS
 digitalWrite(2, LOW);
 digitalWrite(3, LOW);
 digitalWrite(4, LOW);
 digitalWrite(5, LOW);
 digitalWrite(6, LOW);

 }

 //Turn LED ON depending on the byte Read.
 if(byteRead>0){
 digitalWrite((byteRead+1), HIGH); // set the LED on
   }
  }
 }

I'm confused.  What language is this?
Anyway my guess is that you aren't terminating what you send to the Arduino properly (would have helped to see the Arduino code).  The reason I think its this is you are sending a zero after you number.  How does the Arduino know that the zero is not part of the number, do you mean a null or new line?


How to connect Arduino device to Linux? I wrote Arduino sketch and it works. It waits for a command and answers text on response.

Simultaneously, I can't get any response with command line tools.

For example, I have the following code to get temperature:

#!/bin/bash
tty=/dev/ttyUSB0
exec 4<$tty 5>$tty
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
#stty -F $tty 9600 -echo
#printf "temp\n" >&5
echo temp >&5
read reply <&4
echo "$reply"
#tail -n 1 - <&4

It returns empty or hang under different circumstances.

Also, if I run built-in Serial Monitor, I can see responses on command lines like:

echo temp > /dev/ttyUSB0

But I see nothing with commands like tail -f /dev/ttyUSB0

What I am doing wrong?

Add the flag -hupcl to your stty command.  That will disable the assertion of DTR which is resetting the board.

 hupcl (-hupcl)
             Stop asserting modem control (do not stop asserting modem
             control) on last close.

The first time it is run there will be a reset, since setting that flag entails opening the port, which causes a reset.  So you need to add a delay long enough to get past the bootloader - minimum 2 seconds, best make it 3.

You can do that with the sleep command: sleep 3

Note that you now won't be able to upload a new sketch since you have disabled the auto-reset feature that allows you to enter the bootloader, so before uploading a new sketch you need to turn the reset back on with

stty -F $tty hupcl

If you don't disable the reset then every operation in your script that opens and then closes the serial port will trigger a reset of the board.  So in summary try this:

#!/bin/bash
tty=/dev/ttyUSB0
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts -hupcl
sleep 3
echo temp >$tty
read reply <$tty
echo "$reply"
stty -F $tty hupcl


SIM900 random shutdowns I have a SIM900 GPRS/GSM Shield and an Arduino Mega. Now for the past week I have been using USB as power to send and receive GPRS data with no issue. Today the SIM900 module is continually randomly turning off, not even turning of at specific stages of communication.

I thought this could be power related, so have external power (5V 5A UBEC) into the 5V pin of the Mega, which I believe should cover the voltage and current requirements of the SIM900 shield. However this has not solved the problem.

Any ideas on what could be causing the random shutdowns?

EDIT:
Is it safe for me to wire power up like this:

Cool, an UBEC is indeed a smart choice for powering a SIM900.
I could get away with a small switching power supply and just putting in a big capacitor (since the sim900 only draws high current in very short peaks).

But, the limiting factor in this case would be the 6AA batteries. Your UBEC may be able to supply 5A's but those AA's may not.

Also, look up "transient response" (related) according to the related article, you can have an 20A power supply, but still have the voltage drop out when the sim900 starts to transmit. This is because your supply needs to be able to deliver the required 2A in a very short period of time, so basically if your supply can't go from 100ma to 2A fast enough, it'll dip.

I suggest finding a more optimal source as AA's and adding a "big ass capacitor" close to the sim900's input.


Wiring DFRobot LCD shield I need help wiring the DFRobot LCD keypad shield to my Arduino Uno. I plan on making a text-based adventure played on Arduino if that helps.

Solution found here:
http://www.dfrobot.com/wiki/index.php/LCD_KeyPad_Shield_For_Arduino_SKU:_DFR0009

  This example will test the LCD panel and the buttons.When you push the
  button on the shield，the screen will show the corresponding one.
  Connection: Plug the LCD Keypad to the UNO(or other controllers)

/*************************************************************************************

  Mark Bramwell, July 2010

  This program will test the LCD panel and the buttons.When you push the button on the shield，
  the screen will show the corresponding one.

  **Connection: Plug the LCD Keypad to the UNO(or other controllers)**

**************************************************************************************/

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);           // select the pins used on the LCD panel

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons(){               // read the buttons
    adc_key_in = analogRead(0);       // read the value from the sensor

    // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
    // we add approx 50 to those values and check to see if we are close
    // We make this the 1st option for speed reasons since it will be the most likely result

    if (adc_key_in > 1000) return btnNONE;

    // For V1.1 us this threshold
    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 250)  return btnUP;
    if (adc_key_in < 450)  return btnDOWN;
    if (adc_key_in < 650)  return btnLEFT;
    if (adc_key_in < 850)  return btnSELECT;

   // For V1.0 comment the other threshold and use the one below:
   /*
     if (adc_key_in < 50)   return btnRIGHT;
     if (adc_key_in < 195)  return btnUP;
     if (adc_key_in < 380)  return btnDOWN;
     if (adc_key_in < 555)  return btnLEFT;
     if (adc_key_in < 790)  return btnSELECT;
   */

    return btnNONE;                // when all others fail, return this.
}

void setup(){
   lcd.begin(16, 2);               // start the library
   lcd.setCursor(0,0);             // set the LCD cursor   position
   lcd.print("Push the buttons");  // print a simple message on the LCD
}

void loop(){
   lcd.setCursor(9,1);             // move cursor to second line "1" and 9 spaces over
   lcd.print(millis()/1000);       // display seconds elapsed since power-up

   lcd.setCursor(0,1);             // move to the begining of the second line
   lcd_key = read_LCD_buttons();   // read the buttons

   switch (lcd_key){               // depending on which button was pushed, we perform an action

       case btnRIGHT:{             //  push button "RIGHT" and show the word on the screen
            lcd.print("RIGHT ");
            break;
       }
       case btnLEFT:{
             lcd.print("LEFT   "); //  push button "LEFT" and show the word on the screen
             break;
       }
       case btnUP:{
             lcd.print("UP    ");  //  push button "UP" and show the word on the screen
             break;
       }
       case btnDOWN:{
             lcd.print("DOWN  ");  //  push button "DOWN" and show the word on the screen
             break;
       }
       case btnSELECT:{
             lcd.print("SELECT");  //  push button "SELECT" and show the word on the screen
             break;
       }
       case btnNONE:{
             lcd.print("NONE  ");  //  No action  will show "None" on the screen
             break;
       }
   }
}


Arduino CAN SPI Configuration problem I am using an Arduino UNO along with a Cooking Hacks CAN Bus Module and Multiprotocol Radio Shield. The CAN module is connected to the radio shield which is plugged into the Arduino. I got this radio shield keeping future applications in mind where I can combine multiple protocols, for eg. CAN and Bluetooth.

I connected them through an OBD2-DB9 cable to the car's OBD port but noticed that I was not really getting any messages. Well I am getting messages but just:

   -- Constructor Can(uint16_t speed) --
   SPI configured
   The MCP2515 has been successfully reset, configuration mode activated
   Speed=500kps
   -- End Constructor Can(uint16_t speed) --

   Data in buffer 0
   id: 7FF  rtr: FFFFFFFF => Data in buffer 0
   id: 7FF  rtr: FFFFFFFF => Data in buffer 0
   id: 7FF  rtr: FFFFFFFF => Data in buffer 0

After analysing the connections, I realised that the hardware is probably fine since the continuity between the pins of the cables is fine and the CAN module(MCP2515 + MCP2551) is receiving power and I also checked the voltages at the pins and think they're mostly fine apart from a few pins which I'm not sure about. Which brings me to the software issue. I can see that the SPI is not getting configured properly and the MCP2515 controller doesn't enter configuration mode which means the bit times defined are not being used and hence the controller is not initialising like it should. I even tried manually changing to configuration mode by changing the values of the REQOP bits of the CANCTRL register as opposed to doing a software reset which was how I was doing it initially. Even then, no luck. To verify the SPI connection, I chose a random read/write control register like BFPCTRL and wrote a value to it and then read it back to verify that it matched the values I wrote. However, the value read back is not the same as the value I wrote. Also, the controller only has trouble going into configuration mode. It seems to change to normal and listen only mode without problem since the CANSTAT register displays the correct values for the REQOP bits. I don't understand why the controller has problem entering configuration mode but no problem changing to the other modes. Can anybody help me?

SPI Code:

    bool CAN::begin(uint16_t speed)
    {
    #if (DEBUGMODE ==1 )
    Serial.println("-- Constructor Can(uint16_t speed) --");
    #endif

    //Initialization SPI
    SPI.begin();
    SPI.detachInterrupt();
    SPI.setBitOrder(MSBFIRST);
    // both mode 0 & 3 should work
    SPI.setDataMode(SPI_MODE0);

    //Set the SPI frequency
    SPI.setClockDivider(SPI_CLOCK_DIV4);

    #if (DEBUGMODE==1)
    Serial.println("SPI configured");
    #endif

    //Configure MCP2515 pins
    pinMode(CAN_CS,OUTPUT);
    pinMode(CAN_INT,INPUT);
    digitalWrite(CAN_CS,HIGH);

    writeRegister(BFPCTRL, (1<<B0BFM) | (1<<B1BFM));
    int dat = readRegister(BFPCTRL<<2);
    Serial.println(dat);

    //Software resets MCP2515
    reset();
    delay(100);
    //After the reset, controller enters configuration mode
    dispMode();

When I read back the values of B0BFM and B1BFM bits, they should be 1 but the display says that their values are 0.

   void CAN::writeRegister( char direction, char data )
   {
   //CS low to select the MCP2515
   digitalWrite(CAN_CS,LOW);

  SPI.transfer(SPI_WRITE);
  SPI.transfer(direction);
  SPI.transfer(data);

  //CS line again to release
  digitalWrite(CAN_CS,HIGH);
   }

  char CAN::readRegister(char direction)
  {
  char data;
  //CS low to select the MCP2515
  digitalWrite(CAN_CS,LOW);

  SPI.transfer(SPI_READ);
  SPI.transfer(direction);
  //Read data SPI
  data = SPI.transfer(0xff);

  //CS line again to release
  digitalWrite(CAN_CS,HIGH);
  return data;
  }

In SPI protocol you'll need to read the SPI buffer twice because the data you wrote will be read by the IC and the IC will respond to it in the next communication and that's when you know.

Also, by looking at the message, I see that your IC is working fine, but is your CAN bus initialised properly? I'm a FSAE team member and I've faced this issue with the CAN Bus termination resistances and the ODB-II configuration on the Sparkfun CAN Bus shield.

Also, have you tried any other libraries for the CAN Shield? For me the seeedstudio library of their CAN shield worked very well.


Is this circuit risky for an Arduino Uno? I will show a connection diagram between my Arduino Uno and a DSC HS2032 panel (alarm system).
The DSC panel uses 12V and I don't know the voltage fluctuation.
The yellow and green are RX/TX ports.
Github file: https://github.com/taligentx/dscKeybusInterface/blob/master/examples/Arduino/KeybusReader/KeybusReader.ino
DIAGRAM (I assume the vertical "+--+" means a simple "OR" connection):
  DSC Aux(+) --- Arduino Vin pin

  DSC Aux(-) --- Arduino Ground

                                 +--- dscClockPin (Arduino Uno: 2,3)
  DSC Yellow --- 15k ohm res ----|
                                 +--- 10k ohm resistor --- Ground

                                 +--- dscReadPin (Arduino Uno: 2-12)
  DSC Green ---- 15k ohm res ----|
                                 +--- 10k ohm resistor --- Ground

I need to make sure this diagram is SAFE, and will not overheat or do something risky to my Arduino.
Why is this circuit not going to burn my Arduino if it is using 12V?

That circuit is fine as long as the input signals don't go above 12.5V.  You can protect it further by adding a 5.2V zener diode across each of the signals as they enter the Arduino:

simulate this circuit – Schematic created using CircuitLab

Why is this circuit not going to burn my Arduino if it is using 12V?

Because it uses a voltage divider to reduce the voltage to 4.8V.


Is it possible to recover an Arduino if it does not wake up after putting it to sleep I have an ATTiny85 controlling the power to a number of devices. When I first power on it will power the devices via a mosfet. Take the readings it needs to and then puts itself to sleep for 15 minutes then wake up and repeat.

My question is, because I am using the Watchdog timer to put it to sleep, I can't use the reset functionality of the watchdog (ie wdt_Reset). So is there anyway to detect a lock or hang if the ATTiny85 never wakes up for some reason or would I need additional hardware to check for this. If so what kind of circuit would I need.

Thanks

Not sure what you mean by "using the watchdog to put it to sleep". You can sleep with or without the watchdog enabled, and you can even use the watchdog to both wake you with an interrupt and also reset in case of a lockup. Check out section 8.5.2 in the datasheet...

  If WDE is set, WDIE is automatically cleared by hardware when a
  time-out occurs. This is useful for keeping the Watchdog Reset
  security while using the interrupt. After the WDIE bit is cleared, the
  next time-out will generate a reset. To avoid the Watchdog Reset, WDIE
  must be set after each interrupt.


Problem with simple sound detection circuit using a microphone I am very new to this community. My first project with Arduino was using a LDR (light dependent resistor) in a circuit like this:

The input I got was as expected between 0 - 1023.

I then tried a similar project this time using a sound sensor like this:

My circuit is as follows:

A0 on mic to A0 on Arduino
GND to GND
+ve to 5V
LED along with resistor to digital pin 9 on Arduino

My program is as follows:

const int analogInPin = A0;
int sensorValue = 0;

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

void loop() {
  sensorValue = analogRead(analogInPin);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\n");
  if(sensorValue > 900)
    digitalWrite(9,HIGH);
  else
  digitalWrite(9,LOW);
}

The problem is the serial monitor gives a weird reading, randomly giving 1023 and 0 after regular intervals.

sensor = 124
sensor = 0
sensor = 1023
sensor = 39
sensor = 352
sensor = 1023
sensor = 142
sensor = 0
sensor = 1023
sensor = 44
sensor = 338
sensor = 1023
sensor = 163
sensor = 0
...
...

I can't figure out the problem myself so I came here.

I plotted the values you got in a spreadsheet:

You must admit that looks a bit like a sound wave! If you want to know if it is a soft sound or a loud sound you really need to see the maximum values (1023 in your case). If the maximum was 512 then clearly the incoming sound isn't as loud.

An alternative, if you just want loudness would be to filter the incoming signal, eg.

simulate this circuit – Schematic created using CircuitLab

This would smooth the incoming voltage so that consecutive readings would be in a narrower range.

Warning: Judging by the graph, you may be getting negative input into A0. The Arduino pins are not designed for negative voltage. You may want to use a diode to eliminate the negative component.


Remove unwanted characters from char type I'm working on an ESP8266 module that needs to fetch date data from worldtimeapi, everything works fine but the problem is How do I strip of the time field off the datetime JSON response without loop.
Note: Arduino JSON library was used in deserializing the response data and it seems the library only supports char data type.
void loop ()
{
  // Initialize the request object
  HTTPClient request;

// Make a http request
  request.begin(dateTime);
  delay(2000);

  // Check the request status code.
int  responseCode = request.GET(); //Get the api host response code.
  Serial.print("Response code is: ");
  Serial.println(responseCode);
  if (responseCode == 200); // If the server returned OK
  {
      String responseData = request.getString();
      Serial.println("Response from the server is:");
      Serial.println(responseData);
        // Deserialize the JSON response data
       StaticJsonDocument<715> result; // Declare data storage to stack

      //Check for error during data deserialization
      DeserializationError error = deserializeJson(result, responseData);

      if (error)
      {
        Serial.print(F("Response deserialization failed with reason: "));
        Serial.println(error.f_str());
        return;
      }

      else
      {
        char abbreviation = result["abbreviation"];  // Returns the current time zone abbreviation
        char timezone = result["timezone"]; // Returns the current time zone
        char datetime = result["datetime"]; // "2021-03-12T17:04:0
        char date = datetime.remove(9,22); // This line throws error : request for member 'remove' in 'datetime', which is of non-class type 'char'

        Serial.print("Current time is ");
        Serial.print(datetime);
        Serial.print(" ");
        Serial.print(abbreviation);
        Serial.print(" ");
        Serial.println(timezone);
        delay(2000);
      }

  }

}

You can use strtok to split the string on the T character:
char *datepart = strtok(datetime, "T");
char *timepart = strtok(NULL, "T");

Serial.print("The current date is: ");
Serial.println(datepart);
Serial.print("The current time is: ");
Serial.println(timepart);

An alternative is to just find the T and turn it into the NULL terminating character:
char *T = strchr(datetime, 'T');
*T = 0;

If you need to copy the string data into a temporary string first you can do:
char temp[strlen(datetime)+1];
strcpy(temp, datetime);

Then operate on temp instead of datetime.


Does AWG size affect signal from sensors? Would using a thicker cable like 16 AWG affect the signal being received from an RFID or Ultrasonic sensor?

I understand AWG can make a significant impact on voltage when a thick cable is used over a long distance. In my head signal data is delicate so a nice thin wire will ensure little disturbance....

Looked around and couldn't find a clear answer so hopefully someone can help!

A signal is just a varying voltage.  A wire is just a (very long) small resistor.  The device reading the signal is just a current sink.

That's three terms there: voltage, resistance, and current. Three terms you should know are related by Ohm's Law.

Also, some simple rules:

The thinner the wire the bigger the resistance
The longer the wire the bigger the resistance
The more load on the wire the greater the current

And of course, that all means:

The greater the resistance or the greater the current, the greater the voltage drop across the wire.

If the voltage drop gets too great then the device receiving the signal won't be able to work out what it is.

But then of course a wire is also an antenna picking up all sorts of noise. The longer the wire the more noise it will pick up. And the thinner the wire the greater the resistance and the greater the resultant voltage drop, meaning the lower the noise margin and immunity.

So no, a thinner wire isn't better than a thicker wire. The exact opposite is true.


Setup J-K Flip-flop for logging on Arduino RESET There are two events I plan to log; using no switches or requiring manual input of some kind.  One of the events is whenever the Arduino Serial Monitor is opened; the other, is when external event occurs that causes a Arduino RESET.  Second event produces a LOW pulse used to CLK the J-K Flip-flop.  digitalRead of J-K Flip-flop Q; using a conditional statement, if Q = HIGH log to SD Card as event1 date/time stamp else log to SD Card as event2 date/time stamp.  I need the J-K Output Q to be STORED thru the Arduino RESET, so Q can be read.

After reading Q, will need to clear Q; plan to do this from running sketch with a DigitalWrite

74HC73 is the chip I plan to use; it is triggered with a negative going CLK.

What needs to happen with the J and K inputs?  Will this work in toggle mode; with both J and K tried to +5 volts?

Rather than having events that set 1Q or 2Q, consider having the external events take 1R\ or 2R\ low, to reset 1Q or 2Q.  When your sketch starts up, it would read 1Q and 2Q.  If one or the other is low, its event occurred and you can log it.  Then the sketch sets both Q's by dropping the CP lines with J's wired high and K's wired low.  You'd use three I/O pins: two for reading 1Q and 2Q, one for strobing the CP lines to set the Q's after reading them.

Arduino AVR pins default to inputs on Reset so the Arduino can reset without affecting the 74HC73's state.  A 10 to 20KΩ resistor to passively pull the CP lines high is reasonable.

Edit: Note, 1R\ and 2R\ operate asynchronously, and are independent of clock inputs.  This leads to simpler interface requirements for your external events.  However, it may also increase sensitivity to electrical noise; if your system is in a noisy environment a different approach might be needed.


verification error, first mismatch at byte 0x3895 0xdf != 0x44? I bought a SainSmart Arduino Mega 2560. I uploaded a small sketch to it, and it uploaded fine. When I upload a larger sketch though, I get this error:

verification error, first mismatch at byte 0x3895
         0xdf != 0x44

So obviously there's nothing wrong with my bootloader because I can upload smaller files. Why is this happening?

If your sketch contains !!! in it, that can cause some versions of the bootloader to drop into interactive mode, eg.

Serial.println ("Rocket firing!!!");

Also there can be problems with 0xFF bytes in your code causing the bootloader to incorrectly assume that that page of memory was erased, when it was not.

I have a bootloader-uploader sketch at: Atmega bootloader programmer

You need a second board to use it (eg. a Uno) - the bootloader for the Mega2560 is a reasonably up-to-date one. I haven't actually tested it with the Sainsmart version of the Mega, but I presume that internally that part is the same.


Persistence of user input after reboot I am creating an application where user input is required. After a user browses through available choices (via buttons and LCD) depending on the choice of the user a function is run from several available.

When the user reboots the Arduino, it starts from the default function, making the user reselect the choice they want..

Is there a way to have persistence of the choice of the user after a reboot?
So that, when a user makes a selection, after a reboot, the arduino will have this selection (=the function that corresponds to this selection) by default.

Maybe if the user input (the buttons) write to an EEPROM or something like this? So that the arduino reads the value from the component?

If such a solution exists, due to limitations i would like to have only one wire for communication with the device.

EDIT: I am using Arduino Due

Better than that: Zero wires.

The Arduino has EEPROM built in.