text:
Powering 12V keypad through Arduino Uno
Arduino Uno
I'm currently working on a project which will involve entering a sequence on a 12V keypad. The keypad and its documentation can be found here: https://www.jaycar.com.au/digital-keypad-with-rfid-access-control/p/LA5353

They keypad wants 9-18V AC/12~24V DC. I'll be using the keypad to output 26 bit Wiegand to the Arduino. I'm just wondering the best way to power this system. The schematics included with the keypad show that the keypad and the controller  (Arduino) should be sharing a power source. See image attached.
How can I power the 12-24V keypad through the arduino without frying it?

How can I power the 12-24V keypad through the arduino without frying it?

If you power the Arduino with slightly more than 12V (through the barrel jack) then you can get 12V (or slightly less than you power the Arduino with) from the VIN pin.
However the Arduino's on-board voltage regulator does tend to get a little hot when such a high voltage is used to power it. Better is just to power the keypad separately from the correct power source.
And don't forget to connect the grounds together.

Thanks for the information Majenko. So there's no issue with using a seperate power supply for the keypad and then grounding it with the Arduinos ground pin? Also, can i plug the d0 and d1 lines directly into the Arduino, or do i need to manage the voltage?

@SirPattalot none at all.

I appreciate the help. I edited my question after you answered so swiftly, one final question: can i plug the d0 and d1 lines directly into the Arduino, or do i need to manage the voltage?

I think Wiegand is an open drain protocol. Turn on the internal pull-ups of your digital pins and the keypad pulls them down like buttons.

So in that case, direct into Arduino SHOULD be fine?

According to Wikipedia: The Wiegand interface uses three wires, one of which is a common ground and two of which are data transmission wires usually called DATA0 and DATA1, alternately labeled "D0" and "D1" or "Data Low" and "Data High". When no data is being sent, both DATA0 and DATA1 are pulled up to the "high" voltage level — usually +5 VDC. When a 0 is sent the DATA0 wire is pulled to a low voltage while the DATA1 wire stays at a high voltage. When a 1 is sent the DATA1 wire is pulled to a low voltage while DATA0 stays at a high voltage. -- so yes, it's fine.


text:
FIS1100 (IMU)/ I2C/ Arduino
I am a student and currently doing a semester project. The first goal is to get accelerometer and gyroscope data from FIS1100 using the Arduino (Uno). I've got the FIS1100 Evaluation Kit user guide from my supervisor. I've simply separated the sensor PCB from the MCU and connected this sensor to an Arduino Uno as shown on this photo:

The connections are as following:

SCL (on the header of FIS) - A5 (Arduino)
SDA (on the header of FIS) - A4 (Arduino)
GND (on the header of FIS) - GND (Arduino)
3V3-to VIOREF (on the header of FIS) - 3V3 (Arduino)

I wrote this simple code, which I uploaded to the Arduino board. Unfortunately as a result, I got zeros as output.
#include <Wire.h>
const int I2C_address = 0b1101010;
long a_X, a_Y, a_Z;
float g_X, g_Y, g_Z;

long gyro_X, gyro_Y, gyro_Z;
float rot_X, rot_Y, rot_Z;

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

}

void loop() {
  recordAccelRegisters();
  recordGyroRegisters();
  printData();
  delay(800);

}

void setupFIS(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x02);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x08);
  Wire.write(0b10000011);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x04);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x03);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x05);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x06);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x07);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
}

void recordAccelRegisters(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x19);
  Wire.endTransmission(false);
  Wire.requestFrom(I2C_address,6,true);
  //while(Wire.available()<6);
  a_X = Wire.read()<<8|Wire.read();
  a_Y = Wire.read()<<8|Wire.read();
  a_Z = Wire.read()<<8|Wire.read();
  processAccelData();
}

void processAccelData(){
  g_X = a_X/16384.0;
  g_Y = a_Y/16384.0;
  g_Z= a_Z/16384.0;
}

void recordGyroRegisters(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x1F);
  Wire.endTransmission(false);
  Wire.requestFrom(I2C_address,6,true);
  //while(Wire.available()<6);
  gyro_X = Wire.read()<<8|Wire.read();
  gyro_Y = Wire.read()<<8|Wire.read();
  gyro_Z = Wire.read()<<8|Wire.read();
  processGyroData();
}

void processGyroData(){
  rot_X = gyro_X/1024.0;
  rot_Y = gyro_Y/1024.0;
  rot_Z= gyro_Z/1024.0;
}

void printData(){
  Serial.print("Gyro(deg)");
  Serial.print(" X=");
  Serial.print(rot_X);
  Serial.print(" Y=");
  Serial.print(rot_Y);
  Serial.print(" Z=");
  Serial.print(rot_Z);

  Serial.print("   Accel(g)");
  Serial.print(" X=");
  Serial.print(g_X);
  Serial.print(" Y=");
  Serial.print(g_Y);
  Serial.print(" Z=");
  Serial.println(g_Z);
}

So, I really need help to get some relevant data.
And also I have doubts concerning the I2C-address of the FIS1100. In the datasheet of the FIS1100 on page 50 it is said:

the address is 0b1101010 in case when pin SA0 is left unconnected, internally there is a weak pull-down of 200k; the address is 0b1101011 in case when pin SA0 is pulled-up externally.

Now lets go again to user guide and on page 25 (schematic of pull-up/down resistors) we see that SA0 is externally pulled-down.
Question: which I2C-address should I use?

Use a i2c scanner https://playground.arduino.cc/Main/I2cScanner That is the i2c address that you should use. Try to read a status register. According to the datasheet, at startup the sensors are turned off and they will return zero.

Thanks for feedback! I've read the STATUS0 and it gives me 255

Reading STATUS0 seems to start something. What happens when you read the WHO_AM_I register ? How do you read it ? Perhaps a Wire.read() into a byte ? The Wire.read() returns -1 if there is no communication with the sensor, that -1 might turn into 255. Did you run the i2c scanner ?

I think you'll find you need to add some pull up resistors to both connections on the I2C (SDA and SCL).
Also I'm not sure what you should be pulling them up to 3.3v or 5v.  You should check if you need a level shifter or if the device you are connecting is 5v tolerant.
According to you question you should be using the address 0x6A.  0x6B is when you have an external pull up resistor, which I don't think you do have.  So your code is correct.

First, thanks a lot for feedback! Actually if to refer to the user guide (hyperlink in my post) on the page 24 you can see level-shifters. And yes, all the interface pins (SDA, SCL) are pulled properly. Even I used address 0x6A nothing - just zeros. LED on Arduino, which indicates transmission is blinking. Seems like I need to enable I2C or what.... like to give logic 1 maybe somewhere. But it is guessing

source: Stack Exchange

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

sort: votes


text:
Unable to receive and print SMS on the serial monitor with Arduino Uno and SIM900A
I'm trying to receive an SMS and show it on the serial monitor.
My code is as following:
void setup()
{

  Serial.begin(2400);
  Serial.write("AT+CMGF=1\r");           //set GSM to text mode
  delay(1500);

  Serial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
  delay(1000);

  Serial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
  while(1)
  {
    if(Serial.available())
    {
      Serial.write(Serial.read());
    }
  }
}

void loop()
{
}

The circuit diagram is as shown below.

The output that I am getting is as following:
AT+CMGR=1
AT+CMGF=1

OK
AT+CPMS="SM"

ERROR
AT+CMGR=1
AT+CMGF=1

OK
AT+CPMS="SM"

ERROR

ERROR
AT+CMGR=1
AT+CMGF=1

I am not able to use AT+CPMS or AT+CMGL commands.

I put your code inside the code block exactly as it was. Please clean it up because there are extra curly braces.

Your output doesn't match your code.  The output says you are sending CMGR and CMGF in one line, but your code only sends CMGF.

Cleaned the code.

@JRE : please check the updated output.

ERROR SOLVED:For receiving SMS, 5V supply from arduino is insufficient , thus 12v 1 amp supply is required separately.I had faulty adapter, changed it and ERROR got resolved. Though still not able to read messages Because CPMS command  gives 0,20 that means 0 sms present and max memory is 20 SMS.PS: I have SMS stored on sim.

As others have stated, you cannot use the hardware serial port for communication with the device and communication over the USB cable.
OPTION 1
Switch to a different microcontroller, such as the arduino mega with multiple hardware serial ports on board.
OPTION 2
Implement the Software Serial library for communication with the sim card device and use the hardware serial for communication with your computer.
Note: Software Serial implementations are more computationally intensive than the use of hardware serial. Do not expect the same performance from a software serial implementation and do not expect to be able to smoothly run multiple instances of it on a single 8 bit mcu.
Example Code (Untested):
  #include <SoftwareSerial.h>

  void setup()
  {
  Serial.begin(9600);
  SoftwareSerial mySerial(10,11); //RX,TX pins
  mySerial.begin(2400);
  mySerial.write("AT+CMGF=1\r");           //set GSM to text mode
  delay(1500);

  mySerial.write("AT+CPMS=\"SM\"\r");         //Preferred SMS Message Storage
  delay(1000);

  mySerial.write("AT+CMGL=\"ALL\"\r");       //List SMS Messages from Preferred Storage
  while(1)
  {
    if(mySerial.available())
    {
      Serial.write(mySerial.read());
    }
  }
}

void loop(){}

Disconnect from pin 0 and pin 1 and connect to pins 10 and 11 respectively.

The Arduino UNO that you are using only supports one Serial connection (over the TX and RX pins). Since you are using these pins to talk to the device, you cannot also send data over Serial.
Read this article to see more about Serial and how it works on different boards.

So what is to be done as an alternative ?

@Ryhot I'm not sure, there isn't really much that you can do. You could look into getting an LCD display and then you could write the SMS messages to that. Or, alternatively you could just use a MEGA which has more than 1 Serial port. Please up-vote the answer if it helped you!

Here it seems to work . http://www.learnerswings.com/2014/03/read-sms-message-by-at-commands-using.html?m=1

The RX/TX pins are on Uno connected to the USB chip. If you connect a device to RX/TX, you should not use Serial Monitor. It sometimes works, but the device receives the data send to Serial Monitor too and can't process them.
Use SoftwareSerial library for connecting the serial device, if you want to have Serial free for printing to Serial Monitor over USB.

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

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


text:
Using Multiple 4 Digit displays with the same pins
I currently have a ton of 4 Digit 7 Segmented displays(TOFD-5465GGH-B).

The display is driven by a PT6961 LED Driver. Using a Library that I found here I was able to use the display with no issues. The pin out on the display is as such:
1) 5V
2) CS
3) CLK
4) DIN
5) DOUT
6) Common

Since the display has a DOUT does this mean I can run multiple display is series off of the same pins? If so, can someone point me in the right direction to do so. I am currently using a Particle Photon and I am limited as to the number of PWM pins.

Datasheet says?

My understanding is very limited but the datasheet for the PT6961 doesnt state anything about the DOUT. Im assuming you are just supposed to know how to use it. And I am unable to find a datasheet for the Display itself.

If it doesn't say anything about daisy-chaining then it doesn't have daisy-chaining.

That is an SPI interface.  Using multiples should be easy.  Each one has a CS pin.  When that pin is pulled low it selects that chip as the one you are talking to.  Several displays could all share the CLK, DIN, and DOUT pins on the Arduino and each would have it's own pin on the Arduino for CS.  To update any given display, you pull its CS pin low and then transmit your data.  If you pull the CS pins on two displays low at the same time you'll send the data to both.  Whichever has the CS pin pulled low on it is the one that listens.
Google SPI and do a little investigation on SPI with Arduino.  That will help you learn a little about how SPI works and you will certainly get your question fully answered about how to drive multiple chips while sharing pins.  Driving multiple things with the same pins is the whole point of SPI.
The connection would look like this for an UNO -
Pin 13  ----  CLK pin on all chips
Pin 12  ----  DOUT on all chips
Pin 11  ----  DIN on all chips
Choose a different pin on Arduino for each chip and connect to the CS pin.
To use SPI, pin 10 MUST be configured as an output.  It cannot be an input.  So it would be a good idea to use 10 for one of the CS pins just to make sure it is going to stay an output.
EDIT:
I just looked at the page you linked to and it looks like the library you are using isn't using the SPI hardware but is bit-banging SPI from software using other pins.  The concept is still the same, all share CK and DIN and the CS pin picks the one you're talking to.
The code would be a lot faster and much more compact if you changed this library to use the SPI hardware instead of software.  It just limits which pins you have to use to the ones I listed above.
EDIT AGAIN:
I feel generous and it was really really really easy to do so I switched his code to run on the SPI hardware.  It compiles but hasn't been tested.  It should work though.  Hooking DOUT to pin 12 is optional, but you still can't use pin 12 for anything else so you might as well.
PT6961_SPI.h
/*
  PT6961.h - Library for communicating with PT6961 LED driver.
  Created by Garrett Blanton January, 16, 2013.
  Released into the public domain.
*/

#ifndef PT6961_SPI_H_
#define PT6961_SPI_H_

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

class PT6961
{
  public:

    PT6961(uint8_t CS);
    void initDisplay();
    void initRAM();
    void sendCmd(char cmd);
    void sendDigit(char digit, char val);
    void sendNum(int num, char colon);
    void sendDigits(char digit1, char digit2, char digit3, char digit4, char colon);

    const static char _DISPLAY_6X12 = 0x02;
    const static char _DISPLAY_7X11 = 0x03;
    const static char _AUTO_INCREMENT = 0x40;
    const static char _FIXED_ADDRESS = 0x44;
    const static char _DISPLAY_OFF = 0x80;
    const static char _DISPLAY_1_16 = 0x88;
    const static char _DISPLAY_2_16 = 0x89;
    const static char _DISPLAY_4_16 = 0x8A;
    const static char _DISPLAY_10_16 = 0x8B;
    const static char _DISPLAY_11_16 = 0x8C;
    const static char _DISPLAY_12_16 = 0x8D;
    const static char _DISPLAY_13_16 = 0x8E;
    const static char _DISPLAY_14_16 = 0x8F;

  private:

    uint8_t _CS;

};

#endif

PT6961_SPI.cpp
/*
 PT6961.cpp - Library for communicating with PT6961 LED driver.
 Created by Garrett Blanton January, 16, 2013.
 Released into the public domain.
 */

//0 - A
//1 - B
//2 - C
//3 - D
//4 - E
//5 - F
//6 - G
//7 - Colon
#include "Arduino.h"
#include "PT6961_SPI.h"

PT6961::PT6961(uint8_t CS) {

    pinMode(CS, OUTPUT);
    _CS = CS;

    SPI.begin();
    SPI.setBitOrder(LSBFIRST);

}

void PT6961::initDisplay() {
    sendCmd(_DISPLAY_6X12);
    sendCmd(_AUTO_INCREMENT);
    initRAM();
    sendCmd(_DISPLAY_14_16);
}

// Initializes RAM to all zeros
void PT6961::initRAM() {
    //first clear 8 bytes of the display RAM
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);
    for (int i = 0; i < 8; i++) {
//      shiftOut(_DIN, _CLK, LSBFIRST, 0x00);
        SPI.transfer(0x00);
    }
    digitalWrite(_CS, HIGH);
}

// Use to send command based on enumeration
void PT6961::sendCmd(char cmd) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, cmd);
    SPI.transfer(cmd);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendDigit(char digit, char val) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, digit);
//  shiftOut(_DIN, _CLK, LSBFIRST, val);
    SPI.transfer(digit);
    SPI.transfer(val);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendNum(int num, char colon) {
    int digit1 = num / 1000;
    int digit2 = (num % 1000) / 100;
    int digit3 = (num % 100) / 10;
    int digit4 = (num % 10);

    sendDigits(digit1, digit2, digit3, digit4, colon);
}

void PT6961::sendDigits(char digit1, char digit2, char digit3, char digit4,
        char colon) {

    const char DISP[17] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
            0x7f, 0x6f, 0x77, 0x7c, 0x58, 0x5e, 0x79, 0x71, 0x61 };

    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1] | 0x80);
        SPI.transfer(DISP[digit1] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1]);
        SPI.transfer(DISP[digit1]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC2);
    SPI.transfer(0xC2);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2] | 0x80);
        SPI.transfer(DISP[digit2] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2]);
        SPI.transfer(DISP[digit2]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC4);
    SPI.transfer(0xC4);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit3]);
    SPI.transfer(DISP[digit3]);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC6);
    SPI.transfer(0xC6);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit4]);
    SPI.transfer(DISP[digit4]);
    digitalWrite(_CS, HIGH);
}

Example.ino
#include "Arduino.h"
#include <SPI.h>
#include "PT6961_SPI.h"

PT6961 LED(10);   /// This is the pin number for CS pin on each chip
// PT6961 LED2(9);  // The next might look like this if it were connected to pin 9
void setup()
{
     LED.initDisplay();
     Serial.begin(9600);
}

void loop()
{
     //count through 0-9,a-f
     for(int i=0; i<16; i++)
     {
          LED.sendDigits(0,0,0,i,0);
          Serial.println(i);
          delay(500);
     }
}

Thanks. That helped a lot. I got it working only using one extra pin per display now.


text:
Using SPI and 2 shift registers WITHOUT libraries
Arduino Mega 2560 board and SN74HC595 shift register(s). I'm working on a school assignment and having issues getting the shift register(s) working without using Arduino libraries.
I know with the libraries you can use functions such as digitalWrite(....); and shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);.
For my project, I've set up my individual pins as inputs and outputs, but I am having trouble converting the library code into basic code.
IE:
digitalWrite(latchPin, LOW);

can be rewritten as
DDRB &= ~(1 << DDB1);

where latchPin is the SCK pin.
At this stage in the project, we're just trying to get 8 LEDs lit up using 1 shift register, then 16 using 2 shift registers. Any help in understanding what I need to do or direction in which to look would be appreciated.
Thank you,
Nic
Edit:
This is what I have converted from the void setup from https://www.arduino.cc/en/Tutorial/ShftOut12 :
void setup() {
  //Clear the shift registers prev data, Need a low input to reset registers
  //PORTL0 to first SReg SRCLR, PORTL2 to second SReg SRCLR
  //* See data sheet for sn74hc595 shift registers
  DDRL &= ~((1 << PORTL0) | (1 << PORTL2)); //Pg 100 - 21.2.3
  //Use port L0/L2 for SRCLR pin on SReg
  PORTL |= (1 << PORTL0) | (1 << PORTL2); //Pg 100 - 21.2.3

  //Set OE (Enable) to 0 until after last bit is sent
  DDRL &= ~(1 << PORTL4); //Pg 100 - 21.2.3
  //TODO SPI DELAY HERE USING SPDR pg 199

  //Enable SCK as output to drive RCLK and SRCLK on SR
  DDRB &= ~(1 << DDB1); //Pg 96 - 13.4.6
  PORTB |= (1 << PORTB1); //Pg 96 - 13.4.5

  //Enable MOSI as output to drive SER Input on SR
  DDRB &= ~(1 << DDB0); //Pg 96 - 13.4.6
  PORTB |= (1 << PORTB0); //Pg 96 - 13.4.5

  Serial.begin(9600);
  Serial.println("reset");
}

You mention “SPI” in the title, but you are not using the SPI port at all: you are bit-banging. Is this by choice?

The main problem you seem to have is how to implement shiftOut. Well, that's actually quite simple once you understand how shiftOut actually works.
You already know how to set a pin HIGH or LOW - all you lack from that is the concept of time.
All shiftOut does is set the clock and data pins HIGH and LOW at the right time.
It's simply a case of:

Set the DATA pin to HIGH or LOW depending on the bit value to send
Set the CLOCK pin HIGH
Set the CLOCK pin LOW
Go back to 1 for 8 iterations total.

Getting the bit value from a byte can be done with boolean operators & and <<
The basic shiftOut code looks like this:
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

Since your bit order is fixed you can reduce that down to this:
void myShiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(dataPin, !!(val & (1 << (7 - i))));
        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

And then you can replace your digitalWrite calls with direct register manipulation.
void myShiftOut(uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (val & (1 << (7 - i))) {
            PORTB |= (1 << PORTB0);  // Data 1
        } else {
            PORTB &= ~(1 << PORTB0); // Data 0
        }
        PORTB |= (1 << PORTB1);      // Clock HIGH
        PORTB &= ~(1 << PORTB1);     // Clock LOW
    }
}

Note that this code will now run considerably faster than the bloaty digitalWrite based version - so you may find it's now too fast. You may need to include some short delays around the clock HIGH and clock LOW lines. Depending on how long they need to be you could write a little delay loop to introduce a short delay:
void delayLoop(uint32_t iterations) {
    while ((--iterations) > 0) {
        asm volatile("nop");
    }
}

That will delay for iterations clock cycles plus the time taken to do the loop and call the function.  For very short delays it may be better to just insert a few nop instructions:
PORTB |= (1 << PORTB1);      // Clock HIGH
asm volatile("nop");
asm volatile("nop");
asm volatile("nop");
PORTB &= ~(1 << PORTB1);     // Clock LOW
asm volatile("nop");
asm volatile("nop");
asm volatile("nop");

For delaying, you can also #include <util/delay.h> and then _delay_us(0.25) for example.

My strategy: Write the sketch using the standard Arduino library. The goal is have the LED lit up, as you need.
Then, change all standard function calls in your sketch (like digitalWrite) with your own (called it digitalWrite2).
Now implement digitalWrite2 using register manipulation.
Pros:

Divide and conquer. You know have two independent smaller problems (LED and registers).
When is time to implement digitalWrite2 you can learn from your classmate how to do that. I bet that they will start with the hard part (register manipulation).
It makes for a easier debuging. You can compare your own implementation against the standard implementation just by deleting/adding a single "2" in the call.

Of course, taking a look at the Arduino source code will made things trivial :-)
Is that cheating? No, we learn from others, we learn reading other people's code.
Edit: Step by Step Example
Let use Blink to show how to do it:
Original
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

For the new version I will replace pinMode and digitalWrite for the my own  implementation them. How?
Go to the directory where you put your Arduino binaries, which include the source code. There is a subdirectory with the sources (mine is ~/bin/arduino-1.8.3/hardware/arduino/avr/cores/arduino).
There is a file (wiring_digital.c) where I found the source code for pinMode and digitalWrite. Without any shame, I copy-paste and rename.
Note: the original includes a call to turnOffPWM, which I simply comment out, because we will not use it here and I want to cut it short.
That's all.
New version
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode2(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite2(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite2(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

void pinMode2(uint8_t pin, uint8_t mode)
{
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg, *out;

  if (port == NOT_A_PIN) return;

  // JWS: can I let the optimizer do this?
  reg = portModeRegister(port);
  out = portOutputRegister(port);

  if (mode == INPUT) {
    uint8_t oldSREG = SREG;
                cli();
    *reg &= ~bit;
    *out &= ~bit;
    SREG = oldSREG;
  } else if (mode == INPUT_PULLUP) {
    uint8_t oldSREG = SREG;
                cli();
    *reg &= ~bit;
    *out |= bit;
    SREG = oldSREG;
  } else {
    uint8_t oldSREG = SREG;
                cli();
    *reg |= bit;
    SREG = oldSREG;
  }
}

void digitalWrite2(uint8_t pin, uint8_t val)
{
  uint8_t timer = digitalPinToTimer(pin);
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *out;

  if (port == NOT_A_PIN) return;

  // If the pin that support PWM output, we need to turn it off
  // before doing a digital write.
  // if (timer != NOT_ON_TIMER) turnOffPWM(timer); By Look Alterno

  out = portOutputRegister(port);

  uint8_t oldSREG = SREG;
  cli();

  if (val == LOW) {
    *out &= ~bit;
  } else {
    *out |= bit;
  }

  SREG = oldSREG;
}

I understand what you are saying, but this is the issue I am having. Maybe I just don't fully understand the proper way to go about this. As an example, here is a tutorial I found from the Arduino site: https://www.arduino.cc/en/Tutorial/ShftOut12. But how would I go about writing this code in a way that doesn't use Arduino libraries? I've edited my original post to show what code I already have.


text:
Displaying 3 hex bytes sent to serial port on an OLED display
I am new to Arduino and I'm trying my first Pro Mini. I was able to find OLED display code from github that runs perfectly. My problem is trying to show 3 hex bytes sent by a remote control decoder module on the display.
The code will run under serial monitor with serial.print("I Received"); and serial.println(incomingByte, HEX);.
I want to receive this code on the serial port and display it on the OLED screen.
Any help is welcome.
I attached my code any help will be appreciated.
int incomingByte = 0
void setup() (
  Serial.begin(9600)
)

void loop() (
  if (serial.available() > 0) (
    incomingByte = Serial.read();
    u8g.drawStr(10, 37" I Received"); //glcd text position
    u8g.setPrintPos(10,42);
    u8g.print(incomingByte, HEX);
  )
)

This code can't work. You're missing semi-colons, a comma, and replaced {} with (). Good luck with that... You need to fix your code first.

You have to post a complete working example of your code. Your code doesn't even compile.

I fixed all the errors and the code runs fine, thanks for suggestions and ideas. The u8g draw functions would not run in the loop function.

I'm going to assume you know the difference and significance between {} and () and the fact that the code you pasted in had a few syntax issues.
Below is a copy which should compile (I haven't tried it) I added a check to see if Serial.read() returned data, but otherwise its what you had.
int incomingByte = 0;
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    if (Serial.available() > 0)
    {
        incomingByte = Serial.read();
        if (incommingByte != -1)
        {
            u8g.drawStr(10, 37, " I Received"); //glcd text position
            u8g.setPrintPos(10, 42);
            u8g.print(incomingByte, HEX);
        }
    }
}

You've not actually said if the code works or not.  Please can you try this version and report the results.


text:
Error using nRF24L01+ with ATmega328P-PU. Works fine on Uno
I am trying to use a nRF24L01+PA with an ATmega328P minimal breadboard system. I first connected the module to my Uno and verified it with the "scanner" example sketch from the rf24 library, which showed:
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe7e7e7e7e7
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x00
EN_RXADDR    = 0x03
RF_CH        = 0x4c
RF_SETUP     = 0x07
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX

It also shows the readings from each channel after; I just omitted that part.
Removing the chip and reconnecting it to my breadboard ATmega, which has been bootloaded and tested with the blink sketch, I get the following:
STATUS       = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
RX_ADDR_P0-1     = 0x0000000000 0x0000000000
RX_ADDR_P2-5     = 0x00 0x00 0x42 0x42
TX_ADDR      = 0x1042082184
RX_PW_P0-6   = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x00
EN_RXADDR    = 0x00
RF_CH        = 0x00
RF_SETUP     = 0x00
CONFIG       = 0x00
DYNPD/FEATURE    = 0x00 0x00
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = Disabled
PA Power     = PA_MIN

I double-checked all my wires against an ATmega328P pin map and everything checks out.
Furthermore, running the "gettingstarted" sketch on my Uno returns the correct result in the serial monitor where the chip starts in receiving mode and waits for instructions or to receive packets. And because I don't have the other chip set up yet, nothing shows up. However, when I run the exact same program on my breadboard ATmega, I get the following right after it finishes uploading.
RF24/examples/GettingStarted
*** PRESS 'T' to begin transmitting to the other node
Sent response 4194829060
Sent response 4194829060
Sent response 4194829060
Sent response 4294967295
Sent response 4294967295
Sent response 4294967295
Sent response 0
Sent response 4294967295
... yada yada yada

The fact that it is picking up any signals doesn't make sense as I am not transmitting from anything... yet.
The only MAJOR difference between my breadboard setup and the uno is the uno is running off USB 5V and the antenna is getting power from the 3.3V pin. On my breadboard, I have my usb2serial jumpered to 3.3V right off the bat and it is running the ATmega328P with a 16MHz crystal basically at 3.3V (waiting on my 3.3V regulators to arrive this Friday so I can run the chip at 5 and drop down to 3.3 just for the chip, as it is a potential solution I have in mind but in the meantime I am asking for other possibilities). Yes I know it is low but so far other sketches like the blink work, and I am running the chip in receive mode anyways.
I am lost and would appreciate some guidance.
Thank you.

Generally, a debugging question must include both the circuit and the code.   Using a 3.3v output of a serial converter to power a project including a radio is dubious even for the radio version without the power amplifier yours has.  You haven't documented the capabilities of your converter, but typically their regulators can only supply a small amount of current.

The code is what is included in the rf24 library and I'm assuming someone who can offer insight into a fix for the problem probably has used the code before (since they would have used the rf24 library before), so I didn't copy and paste in the huge block of stock code. Regarding the serial converter, if I were to run it at 5V (which I did try later), would the supplied current be noticeably smaller than my Uno? If not, I would think it should work. I tried powering the ATmega @ 5V and using my Uno's 3.3V to power the nrf24 chip. Still same results.

The ATmega328P can't run at 16MHz at a supply voltage of only 3.3V (check the datasheet). Either raise the voltage or lower the frequency.
Also note that 16mHz would be 16 milliherz (16E-3), so you probably mean 16MHz, i.e. 16 megahertz (16E6).
Remember that the nRF24L01+ is a 3.3V device, so don't connect it to the ATmega's Vcc when changing the supply voltage to 5V.
The IO pins are 5V tolerant, so that's not an issue.

Edited the typo. Understood regarding the undervolting. At 16MHz I believe it needs a minimum of 3.7ish, at least per mfg data. But, as some have seen, the board will run at 3.3V and so far the atmega has been able to load sketches at 3.3V so that's why I was sort of ruling out that as the problem.
Got it regarding the nrf24l01 chip voltage. Though if I'm getting a solid 3.3V supply to the nrf24 chip, why does it output all these weird readings. Even the reading of the chip's information is not right. If an undervolted atmega causes these issues, I'd think it wouldn't even print to serial

You don't know that. Behavior outside of the specs is undefined. It may work for a simple blink sketch, and not for more advanced sketches that make use of the SPI peripheral, for example. Last time I tried to run an ATmega328P on 3.3V @16MHz, it worked for 50% of the time.

This is however  unlikely to be the issue.

I jumpered the serialusb to 5V so the breadboard gets 5V so we can rule that problem out. Then i connected the 3.3V and GND from my Uno to the V+ GND of the nrf24l01 chip, so it runs off separate power from the breadboard atmega (IO pins of nrf24l01 5V tolerant so it would be fine getting signals from the atmega at 5V). Still same results with all 0's.

I tried that too and failed too. Then I moved to another project and postponed this for a while, but my web searches suggests, that the NRF needs a lot and hard current sometimes (at start/conneting), and atmega's internal cannot offer that. Also had seen a lot of NRF shields consiting basically only of another foot-print (for breadboard) and 3v3 stabilizer (and requiring 5V power) to believe that it is true. Many people wrote, that those shields works like charm.


text:
Error compiling code for Arduino/Genuino Uno

Arduino: 1.8.6 Hourly Build 2017/10/20 02:33 (Windows 10), Board:
  "Arduino/Genuino Uno"
c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe:
  unable to rename 'core\core.a'; reason: Permission denied
exit status 1 Error compiling for board Arduino/Genuino Uno.
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

Please help me fix this problem. This is my code:
int redled = 6;
int yellowled = 9;
int greenled = 12;

void setup() {
  pinMode (6, OUTPUT);
  pinMode (9, OUTPUT);
  pinMode (12, OUTPUT);
}

void loop() {
  digitalWrite (redled, 1);
  delay(9000);
  digitalWrite (redled, 0); //stopped
  digitalWrite (yellowled, 1);
  delay (3000); // yellowled lights for 3 sec.
  digitalWrite (yellowled, 0);
  digitalWrite (greenled, 1);
  delay (9000);
  digitalWrite (greenled, 0);// greenled starts flashing
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
  delay (500);
  digitalWrite (greenled, 1);
  delay (500);
  digitalWrite (greenled, 0);
}

Why are you running an hourly build? What did you expect?

There are some reports of this error in the Arduino IDE issue tracker: https://github.com/arduino/Arduino/issues/5616 and https://github.com/arduino/Arduino/issues/4683 where it was found to be caused by antivirus software

Explanation is in your question : c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

please use digitalWrite (redled, 1); HIGH and LOW in digitalwrite instead of 1 and 0.

In what way does this answer the question?

The problem is just what the error message says it is.

c:\users\hp\desktop\arduino-nightly\hardware\tools\avr\bin../lib/gcc/avr/4.9.2/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

When you are compiling your code the compilation process is trying to rename a file called core.a (.a means a library). I'm guessing it is doing this because you have changed the board type and it needs to compile the library for that type of board.
You don't have permission to change this file. This could be because:

You don't have Windows security permission.
The file is in use already.
It's because you have installed it on your desktop.

The easiest to check is 2, reboot you machine and start only one instance of the IDE and try again. If it works, something (don't ask what) was accessing the file.
If it doesn't work you need to change the security permissions of the parent folder and all sub folders and files. You will need to Google how to do that, and you will need to search for core/core.a.


text:
ESP8266 (D1 mini) fails to upload sketches
My Setup: 3.3v LiFePo battery attached to G and 3.3 pins. Serial-USB connected.
Result: During the following code the blue on-board LED blinked rapidly for a few seconds then went off. I unplugged it to see if it was programmed but the Blink Sketch didn't run. Any help would be greatly appreciated.
Sketch uses 222,205 bytes (21%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 31,572 bytes (38%) of dynamic memory, leaving 50,348 bytes for local variables. Maximum is 81,920 bytes.
C:\Users\jhoxie\AppData\Local\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd nodemcu -cb 115200 -cp COM3 -ca 0x00000 -cf C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin
**(Everything below this line was highlighted in red)**
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 226352 bytes from C:\Users\jhoxie\AppData\Local\Temp\arduino_build_351972/Blink.ino.bin to flash at 0x00000000
    erasing flash
    size: 037430 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 36% ]
................................................................................ [ 72% ]
..............................................................                   [ 100% ]
starting app without reboot
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete

The uploading seems to work. Please post your code and settings in the IDE. It's not a good idea to connect a battery to the 3.3V pin while plugged into USB.

How do you know the code isn't working?  You might want to check the code is using the correct GPIO port. You upload looks OK, the flashing blue light sounds right, so I think you might be using Arduino Blink.

Thank you for your input. Especially the tip on connecting the battery while connected to usb [tttapa] I finally got it to work by changing the baud rate and messing around with the settings(i.e. board in IDE). I believe I got it to work with the "WeMos D1 R2 & Mini" board whereas I was using the generic esp8266 board.


text:
External Flash Memory for ATtiny85
I'm designing a lightweight circuit, but the ATtiny85 micro-controller I'm using to power it doesn't have nearly enough flash memory to store the code for the devices I'll have hooked up to it (It has 8kb of flash). I was wondering if it'd be possible to have the ATtiny use compiled code from an external flash memory chip of larger capacity elsewhere on the board like its own internal memory. Thanks in advance.

No, it's not possible.
AVR chips can only execute code from their internal flash.

Although you can put a VM in the internal flash and then run bytecode from anywhere.

Well, yes, but only if you're a complete psychopath. Talk about resource wastage on an already resource starved chip...

Although you cannot run code from external (S)RAM, you can:

optimize your code (reducing the number of lines of code by):

use parameterized functions instead of copying/paste code
reduce the type (storage) variables (like constants) which are kept in memory, e.g. instead of 200 integers of 2/4 bytes use 200 bytes
instead of storing const calculated array values, calculate them runtime (causing a performance reduction)
remove unused libraries
strip down used libraries (not needed to remove unused functions)

You could write a small bootloader and load code segments when needed. The internal flash can be written at least 10,000 times so you cannot swap segments too often.
To do this you need to 1) write a bootloader that can load segments from the external flash, 2) partition your sketch into segments, 3) compile and link them to the same address space in program memory, 4) write the segments to the external flash memory.
Extra is handling segment to segment calls as special care is needed by the loader.
An even more elaborate scheme is to allow multiple modules and swap them depending on the execution path (e.g. module to module calls). Segments would be built up of modules, and modules would be reusable between segments. What modules are in memory would depend on some "statistics". This is basically what the instruction cache does in modern processors.
Typical segments could be application level sub-functions such as printing, uploading measurements, etc. Typically functions that are not used very frequently, and where the "background" application is stopped, e.g. data collect.


text:
Arduino Serial Communication with Python: sending an array
I am a bit new to both Arduino and Python. My aim is to send commands to Arduino to run a stepper motor. I need to send an array containing the parameters. After consulting many earlier posts like:
https://stackoverflow.com/questions/27639605/send-a-list-of-data-from-python-to-arduino-using-pyserial
Send multiple int values from Python to Arduino using pySerial
I wrote my Arduino code:
long  incoming[3];

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

void loop() {
  if(Serial.available()) {
    for (int i = 0; i < 3; i++) {
      incoming[i] = Serial.read();
    }
    Serial.println(incoming[0]);
    Serial.println(incoming[0]);
    Serial.println(incoming[2]);
  }
}

And the Python(2.7) code:
from time import sleep
import serial
import struct
ser = serial.Serial('COM6', 9600)

while True:
     ser.write(struct.pack('>iii',2000,10,220))
     print ser.readline()
     sleep(.5)

Now coming to the problem:

The values printed on the Python shell are completely wrong, including negative values.
If I use >BBB instead of >iii, I am getting the correct result, but I can't go beyond 255, the integer limit. There is a small catch here also, the initial two sets are giving minus values and then it becomes alright.
Further, is there any way to interrupt a running void loop?

Any help is deeply appreciated.

Are you aware that Serial.read() returns the first byte in the input buffer? You need to reconstruct your values byte by byte.

This may help clear up some misconceptions: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Also you print incoming[0] twice

If I use >BBB instead of >iii... That's because "B" is a byte. So you end up sending 3 bytes:
struct.pack("BBB", 1, 2, 3)
\x01\x02\x03

"i" is an int and has a size of 4, so you send 4*3 = 12 bytes:
struct.pack("iii", 1, 2, 3)
\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00

Serial.read() reads 1 byte at a time, so you need to read 4 bytes for each value.

Here's a function to read a 32-bit int. The drawbacks of this method are that a) it will block until 4 bytes have been read. And b) there's no way to tell if some data has been lost. There are more robust ways to send data with Start-of-Message, End-of-Message, and Check-sum chars. Also, the function assumes the data is sent with the LSB first. But I'll just put this here as an example.
// Helper macro to merge 4 bytes
#define TO_INT32(a,b,c,d) (((d)<<24)|((c)<<16)|((b)<<8)|(a))
int32_t read_int()
{
  uint32_t result[4];
  for (int i = 0; i < 4; i++) {
    // Wait for data at the port
    while (!Serial.available());
    result[i] = Serial.read();
  }
  return TO_INT32(result[0], result[1], result[2], result[3]);
}

You can much more easily send an array between Python and Arduino using the inter-compatible libraries SerialTransfer.h and pySerialTransfer. Using libraries like this ensures reliable and robust communication between Python and your Arduino.
SerialTransfer.h is installable via the Arduino IDE's Libraries Manager and comes with many examples. The package pySerialTransfer is pip-installable.


text:
Beetle ble with SD card reader
I just started working on a project involving bluno beetle ble. For now, i'm sending the data from beetle to a android app i made.
But, for a fail safe mechanism in case the mobile is not in range or has disconnected from the device, i want to add a SD card reader to the device so i can save the data.
Is it really possible to add SD card reader to beetle ble? If yes, can someone provide any hint on what connections need to be made?
Thanks

Have you found an answer to this?

@RichardWinter check the answer

Eventually I got it working. The connections that i made are as follows:

SDA pin on beetle -> SDA pin on SD card module
SCL pin on beetle -> SCL pin on SD card module
GND pin on beetle -> GND pin on SD card module
VCC pin on beetle -> VIN pin on SD card module

Then upload the sample code present on arduino IDE, or you can find it here as well: https://www.arduino.cc/en/Tutorial/ReadWrite
There we go!
EDIT: The soldering is tricky for bluno beetle. Detailed instructions can be found here :


text:
Error while creating file on sd card
I want to create a file and read it form sd card by arduino. I have used sd card module. I have used this following code. In serial monitor it says "SD card is ready to use." But it can't read or write files. I have formatted the card in FAT32 format.
My code is :
#include <SD.h>
#include <SPI.h>

int CS_PIN = 10;

File file;

void setup()
{

  Serial.begin(9600);

  initializeSD();
  createFile("test.txt");
  writeToFile("This is sample text!");
  closeFile();

  openFile("test.txt");
  Serial.println(readLine());
  Serial.println(readLine());
  closeFile();
}
void loop()
{
}

void initializeSD()
{
  Serial.println("Initializing SD card...");
  pinMode(CS_PIN, OUTPUT);

  if (SD.begin())
  {
    Serial.println("SD card is ready to use.");
  } else
  {
    Serial.println("SD card initialization failed");
    return;
  }
}

int createFile(char filename[])
{
  file = SD.open(filename, FILE_WRITE);

  if (file)
  {
    Serial.println("File created successfully.");
    return 1;
  } else
  {
    Serial.println("Error while creating file.");
    return 0;
  }
}

int writeToFile(char text[])
{
  if (file)
  {
    file.println(text);
    Serial.println("Writing to file: ");
    Serial.println(text);
    return 1;
  } else
  {
    Serial.println("Couldn't write to file");
    return 0;
  }
}

void closeFile()
{
  if (file)
  {
    file.close();
    Serial.println("File closed");
  }
}

int openFile(char filename[])
{
  file = SD.open(filename);
  if (file)
  {
    Serial.println("File opened with success!");
    return 1;
  } else
  {
    Serial.println("Error opening file...");
    return 0;
  }
}

String readLine()
{
  String received = "";
  char ch;
  while (file.available())
  {
    ch = file.read();
    if (ch == '\n')
    {
      return String(received);
    }
    else
    {
      received += ch;
    }
  }
  return "";
}

You might want to use SD.begin(CS_PIN) instead of SD.begin().

tried it. but same problem :/


text:
ESP8266 - AP+STA mode not working properly
I'm trying to have an ESP8266 ESP-12 to serve as Access Point and Station at the same time, delivering the same webpage in both cases.
This is what I have:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <EEPROM.h>
#include <DNSServer.h>
#include <ESP.h>

const byte DNS_PORT = 53;
DNSServer dnsServer;

MDNSResponder mdns;
ESP8266WebServer server(80);

String ssid = "";
String password = "";
String webPage = "";

void setup(void){

  IPAddress Ip(192, 168, 1, 1);
  IPAddress NMask(255, 255, 255, 0);
  WiFi.softAPConfig(Ip, Ip, NMask);
  WiFi.softAP(conf_ssid.c_str());
  WiFi.mode(WIFI_AP_STA);
  Serial.begin(115200);
  delay(1000);
  Serial.println("");
  Serial.println("Soft AP Started");
  Serial.println("");

  /* Setup the DNS server redirecting all the domains to the Ip */
  dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
  dnsServer.start(DNS_PORT, "www.example.com", Ip);

  //connectToWifi();
  getCredentials(); //Reads Home WiFi credentials from the EEPROM
  if (ssid != "" and password != ""){
    WiFi.begin(ssid.c_str(), password.c_str());
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    WiFi.mode(WIFI_AP_STA);
  }
  server.begin();

  // When no password is present
  if ((ssid == "" and password == "") or (ssid == "Error")){
    // ****** MAIN PAGE ******
    server.on("/", [](){ /* HANDLES CREDENTIAL INPUT */   });
    server.begin();
  }
  else // If we have ssid and password -- check if we have connection
  {
    webPage += "
Main Webpage
";
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    server.begin();
    //if (mdns.begin("esp8266", WiFi.localIP())) {
     // Serial.println("MDNS responder started");
    //}

    server.on("/", [](){
      server.send(200, "text/html", webPage);
    });
    Serial.println("HTTP server started");
  }
}

void loop(void){
  dnsServer.processNextRequest();
  server.handleClient();
}

Basically, it reads the credentials from the EEPROM, if there is no credential, a WiFi configuration page is displayed, otherwise it also connects to the WiFi serving the Main Webpage to both AP and Station.
The issue is that, even though I can see the AP and a ping from my PC to the WiFi Station's Ip works, I can only access the webpage if I'm connected via AP, not via Station.
Any thoughts?
Many thanks.

how did you find out the IP address of STA?

would not one server.begin() at the end of setup be enough?

The STA IP is retrieved via serial console. And having only one server.begin() gives the same result, that was just me trying something different when I tried to reset the esp whenever the configuration changed

You know https://github.com/tzapu/WiFiManager  ?

What is the IP and default gateway of your PC?

@Juraj I'm gonna check that.

@Code Gorilla, why do you need that?what are you thinking?

I was wondering if it could be a simple routing issue rather than actually a problem with you code.  When you connect via the station I guess there is another access point involved and unless you have got the routing write it will do what you describe.  (Yeah I don't actually want you IP and gateways address - well done for not posting them :) )

@Code Gorilla thanks, I'm not sure that I followed your thought, but I'll try playing around with gateways and stuff and came back with the results

@CodeGorilla I've been thinking on your solution, but I think that this is not the case, since I can connect through my PC when I don't try to make both connections work at the same time. Any other idea?

Some additional information: the only goal on this is to be able to know the IP of the ESP so I can find it on the net, if there is any other solution to this, please let me know. Thanks

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


text:
Low cost IR sensor based finger gesture recognition controlled wheelchair
I am doing a project in which three IR sensors are used for getting three fingers's gesture to control the movements (left, right, forward, backward) of two motors.
The threshold value of IR sensor output is 450 mV for getting  signal to be passed.
I am not understanding how to design different conditions for different movements of motors
int firstanalogPin = 1;     // Infrared Sensor (Right lead) connected to analog pin 1

int val1 = 0;           // variable to store the value read

int enablePin = 1;
int LeftMotorForward = 10; // Pin 10 has Left Motor connected on Arduino boards.
int LeftMotorReverse = 9; // Pin 9 has Left Motor connected on Arduino boards.

int RightMotorForward = 12; // Pin 12 has Right Motor connected on Arduino boards.
int RightMotorReverse = 13; // Pin 13 has Right Motor connected on Arduino boards

void setup()
{
    pinMode(LeftMotorForward, OUTPUT);  // initialize the  pin as an output.
    pinMode(RightMotorForward, OUTPUT);  // initialize the  pin as an output.
    pinMode(LeftMotorReverse, OUTPUT);  // initialize the  pin as an output.
    pinMode(RightMotorReverse, OUTPUT);  // initialize the  pin as an output.
    Serial.begin(9600);          //  setup serial
}

void loop()
{
    val1 = analogRead(firstanalogPin);    // read the input pin
    Serial.println(val1);                           // debug value

    if (val1 >700) // forward
        digitalWrite(LeftMotorForward, HIGH);
    else
        digitalWrite(LeftMotorForward, LOW);   // turn the Left Motor ON
    if (val1 >700)
        digitalWrite(RightMotorForward, HIGH);// turn the Right Motor ON
    else
        digitalWrite(RightMotorForward, LOW);// turn the Right Motor ON
}

you need only one if-else block .... just turn on both motors in the first if block

What is it that you have a problem with?  You have made the motors move forward.  So if you want just 3 different exclusive motions Forward, Left, Right.
What you could do is have 1 finger control the direction, 1 finger control left and 1 control right.
   OFF       ON
F1 Forwards  Backward
F2 Left Off  Left On
F3 Right Off Right On

So to go straight forwards F2 & F3 have to be greater than 700.
To turn left F3 > 700 && F2 < 700  (Right motor on will make the chair turn left)
To reverse then you need F1 > 700.
etc.
Ensure that the conditions are if/else ifs otherwise its going to get messy.


text:
add 0x to a byte
I have a byte variable CardNumberByte with a value of E8 if i print out as HEX:
Serial.println(CardNumberByte, HEX)

which returns E8.
What I would like to do is to "append 0x as prefix" so that it is equivalent to
Char CardNumberByte=0xE8;

how should i concatenate 0x to CardNumberByte?
here is the reason i need to do so.
Thanks

Did you try just printing it first?

no, i need a char variable with the value of 0x28, not just 28 printed out using HEX format in the example. 0x28 will be an address for the sensor

That's a completely different question from what you're asking.

Please edit your question to reflect what you actually need help with.

"How do I convert a string with two hexadecimal digits to a byte?"

I'm voting to close this question as off-topic because very elemental programming question unrelated to Arduino

I think there is a serious basic misunderstanding of very elementary C (and even basic programming and even "what a computer is") concepts here. You need to go right back to basics and learn how to count (metaphorically) before you start tacking calculus.

The whole idea of "add a prefix to a byte variable and store it in the byte variable" is completely meaningless.

I've looked at you question and the question you linked two and I've tried to join the dots to give you an answer, so I might be well off the mark, but...
I think you might have misunderstood what 0x28 means.
0x?? means that the ?? represent a hexadecimal number rather than a decimal number.
So 10 (Ten) in decimal is the same as 0x0A in hex or B00001010 or in binary or even 012 in octal.  (See https://www.arduino.cc/en/Reference/IntegerConstants for more details)
So you want to have some code that says:
char Address = 0x28;

This is assigning the hexadecimal value 28 to the variable Address.  You could also write:
char Address = 40;

In this case you are assigning the value decimal 40 (which is hex 28) to the variable.  If you want to write strange code that is misleading you could write:
char Address = '(';  // ( is ASCII character 0x28 or 40 - Don't do it like this!

One other important thing here is that the char type in this case is not being used as type that holds a printable character, its being used as a signed 8 bit number.

The answer to the question you asked is:
Serial.print("0x");
Serial.println(CardNumberByte, HEX);

But what you want to do according to the comment you posted is parse "E8" to give you 0xE8.
int parseHex(char* input){
    int result = 0;
    while(input && *input){
        if(*input >= '0' && *input <= '9'){
            result <<= 4;
            result+= *input - '0';
        }
        if(*input >= 'a' && *input <= 'f'){
            result <<= 4;
            result+= *input - 'a'+10;
        }
        if(*input >= 'A' && *input <= 'F'){
            result <<= 4;
            result+= *input - 'A'+10;
        }
        input++;
    }
    return result;
}

You forgot to advance input and check if it's \0 before shifting.

Why are you using: input <<= 4; on pointer?

@KIIV because I was far too hasty...

I think you should use: result = result<<4 + ... or at least move that bitshift before the result += ....

Here you have:
  char buffer[20];
  snprintf(buffer, sizeof(buffer), "0x%X", 1234);
  Serial.println(buffer);

You have to study the classic C print functions.


text:
waking up arduino mini with a external signal
I have an arduino mini with an ultrasonic sensor conected to the pins 2 and 3, and a RGB LED connected to the 4,5, and 6, I want to include a wake up and sleep functionality that wakes up when receive a high signal in another pin as 7.
I have seen that normaly the pins for that are 2 and 3, as in the arduino web: Arduino sleep web
But can it be done with another pin?

As well as the normal external interrupts INT0 and INT1 you can also wake the chip through a variety of other interrupts. One of those is the pin change interrupt.
In the datasheet is a table of what is available in the different sleep modes, and what can wake you from that sleep mode. I have compressed the table to remove a lot of the stuff you don't care about at the moment and just show the "wake-up sources":

As you can see both INT and PCINT can wake from all modes (along with TWI [Wire.h] slave mode address matching).
The note (3) on the table just says that for INT0 and INT1 it must be a LOW level interrupt, not a RISING or FALLING. No mention is made of the type of interrupt for PCINT.
So yes, since pin 7 has PCINT facilities (all pins on the ATMega328P have PCINT) you can configure that as a wake-up source and wake the MCU using pin 7.

Arduino Mini has only two interrupt capable pins: 2 and 3. You have to move your sensor to other pin.
From the AtMega328p datasheet:

If a level triggered interrupt is used for wake-up from Power-down,
  the required level must be held long enough for the MCU to complete
  the wake-up to trigger the level interrupt. If the level disappears
  before the end of the Start-up Time, the MCU will still wake up, but
  no interrupt will be generated. The start-up time is defined by the
  SUT and CKSEL Fuses.

You forgot PCINT...

@Majenko. You are right. Your answer is better. What do i do?

There's not a lot you can do besides plagiarise ;) It's up to the OP to do whatever he fancies.


text:
Interface Processing with Arduino to operate a servo by MouseX
I want to make a servo change its angle using my mouse. When I move mouse horizontally the servo should change its angle correspondingly.
This is the sketch I wrote, unfortunately the servo doesn't move one bit. HELP.
Processing Code:
import processing.serial.*;
Serial port;
void setup() {
  size(256, 150);
  println("Available serial ports:");
  // if using Processing 2.1 or later, use Serial.printArray()
  println(Serial.list());
  port = new Serial(this, Serial.list()[1], 9600);
}

void draw() {
  // draw a gradient from black to white
  for (int i = 0; i < 256; i++) {
    stroke(i);
    line(i, 0, i, height);
  }
  // write the current X-position of the mouse to the serial port as
  // a single byte
  port.write(mouseX);
  println(mouseX);
}

Arduino Code:
#include <Servo.h>
Servo myservo;
void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
  // initialize the servo:
  myservo.attach(10);
}
void loop() {
  byte pos;
  // check if data has been sent from the computer:
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    pos = Serial.read();
    // set the angle of the servo:
    myservo.write(map(pos, 0, 255, 0, 180));
  }
}

Welcome to Arduino:SE. What exactly is your problem here? What do you expect the code to do? What does it actually do? What have you tried to diagnose the problem? Please help us to help you.

Hi @sempaiscuba, thanks for replying. I'm trying to operate a servo using Arduino and Processing. what I wanted it to do was, i'd move my mouse horizontally on a canvas and the servo would change the angle accordingly and simultaneously.
The problem is the Servo isn't moving at all, the circuitry is fine.

Arduino side looks fine. This is most likely a Processing problem, not an Arduino problem.

@Majenko I Didn't see that coming, I thought Processing was fine. Wait, is it because, mouseX is more of an int than a Byte?

This, println(Byte.valueOf(Integer.toString(mouseX))); brings out an error: Value out of range. Value: 128, Radix 10.

Edit your question to explain what you're actually asking.

@per1234 done..

What version of Processing are you using? I just tested this with v3.3.6 and it works ok. (I didn't hook up a motor, just displayed the values and they were 0-255).

When you try and solve a problem you want to focus on just one part at a time.  If I have understood what you are doing correctly then you are trying to:

Get a computer to talk to an Arduino over serial
Get an Arduino to position a servo
Get an Arduino to decode information sent by the computer
Get the computer to code the information
Get the computer to draw graphics.

You can try and ice a cake, feed a baby, talk on you mobile and drive a truck all at the same time, it doesn't mean its a good idea.  When you crash what was the cause?  You haven't got a clue, you were too busy trying to do all that not analyse what is happening at the same time.
So, what I'm trying to say is break it down.  Normally with motors the problem is related to power, people assume that the Arduino can provide enough power for a servo, that's not always the case.
I would:

Write a program that sets the servo to 10 hard coded positions.
Write a program that sets the servo to the position manually entered on the command line.
Write a program that draws the gradient, interprets the user entry and writes the command to be sent to the Arduino to the command line.
Write a program that runs on the Arduino and echoes what it receives over the serial line to some "other output mechanism"  (Connecting the computer via SoftwareSerial might be a good idea).

And once they are all working as you expect connect them all together and it will all magically work :)
(Sorry if I'm teaching you to suck eggs, if you have already done all this ignore me)


text:
ATmega8L power issue
I am doing a prototype using ATmega8L-8PU to detect temperature and control a relay and buzzer, but the schematic seems not work, therefore I do a simple test to verify the AVR's pins are working perfectly or not.
I using the example sketch - Blink to control Digital-13 to let LED blink. It is work.
Then I do a second sketch to test all pins (Due to leak of LED, I test first 8 pins.) It failed. Second Sketch is quite simple and strict forward: blink D0-D7 LED one by one.
char i, j, pcnt = 1;

char startDigitalPin = 0;
char maxDigitalPin = 7;

void setup()
{
    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    digitalWrite(13, HIGH);
    delay(100);
    digitalWrite(13, LOW);
    delay(100);

    // put your setup code here, to run once:
    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        pinMode(i, OUTPUT);
        digitalWrite(i, LOW);
    }
}

void loop()
{
    // put your main code here, to run repeatedly:
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);

    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        for(j=i; j<=maxDigitalPin; j++) {
            digitalWrite(j, HIGH);
            delay(100 * pcnt);
            digitalWrite(j, LOW);
            delay(100 * pcnt);
        }

        digitalWrite(i, HIGH);
        delay(200 * pcnt);
    }

    pcnt++;

    if(pcnt > 10) {
        pcnt = 1;
        delay(8000);
    }
}

Question:

Why I using Blink example sketch, D13 is work fine, the LED light on with normal bright.
Why second sketch, the D13 LED super dark, but it light on.

Check it out these 2 videos in youtube.
https://www.youtube.com/watch?v=sknNPxqg5zc
https://www.youtube.com/watch?v=KWsdP3egsvY
I have burn a bootloader to ATmega8L-8PU (Summary Datasheet) using Arduino IDE 1.6.5 with MiniCore, Config: ATmega8 External 8MHz.
Parts in my bearboard using:

ATmega8L-8PU
2 x 22pf
1 x 100nf
1 x 8MHx crystal
9 x LED with 330Ohm resistor

You forgot the pinMode for pin 13, perhaps the led is blinking very dark with the internal pullup resistor of 50k. The MiniCore is not the official Arduino core. I think the OptiBoot comes with a small bootloader for the ATmega8, and perhaps you need an extra board in "boards.txt", but you can use the normal Arduino software. The resulting code is already small (don't use floating point). I see no need for a special MiniCore.

You forgot pinMode(13, OUTPUT) in the setup.

Post your schematic.

I tested your sketch after adding pinMode(13, OUTPUT) in the setup, and it works as you intended.
But, as you don't post your schematic, I was only able to chech on-board LED blinking.
void setup()
{
  pinMode(13, OUTPUT);

  for (int i=0; i < 3; i++) {
      digitalWrite(13, HIGH);
      delay(100);
      digitalWrite(13, LOW);
      delay(100);
  }

    // put your setup code here, to run once:
    for(i=startDigitalPin; i<=maxDigitalPin; i++) {
        pinMode(i, OUTPUT);
       digitalWrite(i, LOW);
    }
}

I also reduce your code using a for loop.


text:
Powering Arduino Pro Mini with different voltage, fuse setting
Arduino Pro Mini commonly comes in two packages, 5V 16MHz and 3.3V 8MHz.

The only difference between those two boards are regulator and clock crystal, right?
What happens if I supply 2V to VCC pin of 5V 16MHz board?
What happens if I supply 2V to RAW pin of 5V 16MHz board?
What happens if I supply 5V to VCC pin of 3.3V 8MHz board?
What happens if I supply 5V to RAW pin of 3.3V 8MHz board?

I read from some websites stating that Arduino Pro Mini power consumption can be reduced by removing regulator.

Does removing regulator cause VCC pin = RAW pin?

Jean created a custom board for Arduino Pro Mini rated at 1MHz 1.8V.

Which pin should I supply voltage after changing fuse setting? (Jean changed the fuse setting but I am not sure where to connect the supply voltage of 1.8V)
Related to question 7, is there a need to remove regulator to supply 1.8V?
Can I supply higher voltage (3V) on board with 1.8V fuse setting?

Reason for question/ Confusion
I want to power Arduino Pro Mini using 3V coin cell. Battery voltage decreases after usage to around 2V. I am thinking of simply inserting 3V coin cell to Arduino with 1.8V setting. But regulator may hinder the operation. That is why I am confused. Sites I visited states the possibility of using lower voltage after changing fuse setting but did not mention where to connect and whether regulator need to be removed.
Furthermore, ATmega328p datasheet states the VCC range is 1.8V to 5.5V. If that is so, why not just plug those voltage to VCC pin of Arduino Pro Mini instead of specifically 5V or 3.3V. Question 1-5 should clear my confusion on this.

Read the datasheet once more. A certain voltage is needed for a certain clock frequency. There is a graph somewhere.
Since the Atmega328p is able to run up to 5.5V for VCC, that 5.5V is for every clock frequency.
Using 2V for VCC is not enough to run it at 16MHz. According to the datasheet even 3.3V is not enough. But 3.3V and 16MHz will work (it is outside the specifications though).
The RAW pin is the voltage before the voltage regulator, right ? Depending on the voltage regulator you can apply a large range of voltage.
See the pinout.
When you remove the voltage regulator, the RAW pin is open. Sometimes I remove the voltage regulator and use 3 AA batteries and feed the 4.5V into the VCC (or 5V pin) of a 8MHz ATmega328p board.

Yes. The bootloader and sketch have to know the clock frequency. A sketch compiled for 8MHz is for a 8MHz Arduino board and a sketch compiled for 16MHz is for a 16MHz Arduino board.
2V is too low. 3.3V should work.
2V is too low. 3.3V depends on the voltage regulator.
No problem. The voltage regulator gets a reverse voltage.
No problem.
No. See the schematic.
To VCC.
Not a "must", but it is highly preferred to remove the voltage regulator, so no current is leaking towards the voltage regulator which gets a reverse voltage.
Yes. The fuses are to lower/disable the BOD, so a higher voltage is no problem.

This is the best tutorial about the power of the Atmega328p : Nick Gammon about Power
ADDED
I forgot to mention to remove the led as well.
This is a Pro Mini with a coin cell.
Lowering the clock speed will make it run at lower voltages, but that will not always reduce the used energy. Doing a calculation at a slow speed takes more time than the same calculation at high speed (and going into sleep mode after that).
ADDED 2
When a low voltage is supplied (for example 2V to a 5V 16MHz Arduino board), the voltage regulator will not work. How much current/voltage is still passed on depends on the voltage regulator. With the BOD disabled, and the microcontroller runs below its required voltage, anything weird can happen. Parts of the chip will work and parts will not. That is why the BOD was invented in the first place (to reset the chip and avoid weird things to happen). I think it is very unlikely that the microcontroller will get damaged with a (too) low voltage.

so if i want to supply 2.5~3V to Arduino Pro Mini, I'll have to reduce the clock frequency and remove the regulator, correct?

Yes, that is correct. For testing your sketch, you don't have to desolder the voltage regulator right now. Just use VCC and ignore the leakage current to the voltage regulator.

Thank you for the clarification. One last question. What happens if i feed a lower voltage on a regulated Arduino? i.e feeding 2v on 5V regulator (assuming clock frequency is ok). will it stress the battery or voltage regulator or arduino?
Edit - okay. that answered my last question. thanks

I have added a ADDED section. Someone uses a coin cell. I prefer three AA batteries. No stress with a lower voltage to the regulator. I will not work, that's all.

ADDED 2 section added.

Can't use three AA as size matter in my project. Otherwise, I could have used li-ion and step up to 5V for easier usage. ADDED 2 well answered my question. More things to read (BOD and gammon tutorial). yay


text:
Sparkfun Spectrum Analyzer: Problems with frequency bands
I bought around 2 years ago the Spectrum Analyzer Shield from Sparkfun, but I never had the time to do something with it. Recently I found the time to start a project to build a graphical equalizer. For that I use the Spectrum Analyzer Shield to split the left and right audio channel into 7 different bands. After I finished to build my first LED-Matrix panel and tested it out with the Spectrum Analyzer Shield I thought that everything works as it should. I made than the second LED-Matrix panel and tested everything again. Well, the result was odd. I noticed that the order of the bands inside of my arrays are switching around between every restart of my Arduino. Here are two example outputs. I played a 64 Hertz tone and expected to see an increase for the right and left channel for the first band.
Band0 R:70 ,L: 76 | Band1 R:92 ,L: 81 | Band2 R:548 ,L: 83 | Band3 R:108 ,L: 575 | Band4 R:76 ,L: 108 | Band5 R:64 ,L: 82 | Band6 R:63 ,L: 83 |
Band0 R:67 ,L: 78 | Band1 R:87 ,L: 83 | Band2 R:552 ,L: 82 | Band3 R:108 ,L: 575 | Band4 R:80 ,L: 109 | Band5 R:68 ,L: 83 | Band6 R:63 ,L: 78 |
Band0 R:77 ,L: 75 | Band1 R:88 ,L: 78 | Band2 R:546 ,L: 83 | Band3 R:105 ,L: 575 | Band4 R:79 ,L: 109 | Band5 R:61 ,L: 79 | Band6 R:59 ,L: 77 |
Band0 R:73 ,L: 74 | Band1 R:92 ,L: 85 | Band2 R:546 ,L: 84 | Band3 R:113 ,L: 572 | Band4 R:78 ,L: 105 | Band5 R:58 ,L: 74 | Band6 R:65 ,L: 78 |
Band0 R:71 ,L: 77 | Band1 R:92 ,L: 82 | Band2 R:550 ,L: 84 | Band3 R:107 ,L: 573 | Band4 R:76 ,L: 107 | Band5 R:59 ,L: 76 | Band6 R:59 ,L: 79 |

After restart of the arduino (pressed 5 sec the reset button)
Band0 R:71 ,L: 576 | Band1 R:86 ,L: 106 | Band2 R:545 ,L: 87 | Band3 R:107 ,L: 82 | Band4 R:76 ,L: 78 | Band5 R:55 ,L: 80 | Band6 R:61 ,L: 79 |
Band0 R:71 ,L: 575 | Band1 R:83 ,L: 105 | Band2 R:549 ,L: 80 | Band3 R:109 ,L: 87 | Band4 R:75 ,L: 79 | Band5 R:55 ,L: 84 | Band6 R:64 ,L: 78 |
Band0 R:69 ,L: 575 | Band1 R:88 ,L: 103 | Band2 R:546 ,L: 79 | Band3 R:109 ,L: 82 | Band4 R:73 ,L: 79 | Band5 R:63 ,L: 78 | Band6 R:62 ,L: 84 |
Band0 R:70 ,L: 575 | Band1 R:87 ,L: 103 | Band2 R:547 ,L: 84 | Band3 R:106 ,L: 82 | Band4 R:76 ,L: 78 | Band5 R:61 ,L: 80 | Band6 R:61 ,L: 90 |
Band0 R:71 ,L: 574 | Band1 R:83 ,L: 106 | Band2 R:550 ,L: 79 | Band3 R:109 ,L: 84 | Band4 R:77 ,L: 77 | Band5 R:57 ,L: 85 | Band6 R:60 ,L: 81 |
Band0 R:64 ,L: 576 | Band1 R:92 ,L: 109 | Band2 R:549 ,L: 80 | Band3 R:105 ,L: 80 | Band4 R:75 ,L: 72 | Band5 R:56 ,L: 76 | Band6 R:60 ,L: 80 |

I experienced the same issue with the source code from Sparkfun: https://github.com/sparkfun/Spectrum_Shield/blob/HW_1.6_FW_1.1/Firmware/SparkFun_Spectrum_Demo/SparkFun_Spectrum_Demo.ino
I modified this code only slightly to log everything.
void Read_Frequencies(){
  //Read frequencies for each band
  for (freq_amp = 0; freq_amp<7; freq_amp++)
  {
    Frequencies_One[freq_amp] = analogRead(DC_One);
    Frequencies_Two[freq_amp] = analogRead(DC_Two);
    digitalWrite(STROBE, HIGH);
    digitalWrite(STROBE, LOW);

    Serial.print("Band");
    Serial.print(freq_amp);
    Serial.print(" R:");
    Serial.print(Frequencies_One[freq_amp]);
    Serial.print(" ,L: ");
    Serial.print(Frequencies_Two[freq_amp]);
    Serial.print(" | ");
  }
  Serial.println("");
}

Hopefully I'm doing something fundamental wrong, if not that would mean I have to buy a new Shield :/


text:
Can I use the Arduino Uno's 3.3v pin while powered by a 9 volt battery?
I have an Arduino Uno. It has a 3.3v pin that I would like to use to power another module that requires 3.3v, and nothing more. If I power my Arduino Uno with a 9 volt battery, will this pin output 3.3v, or will it give more than that?

It will output 3.3V. What module do you want to power ? A sensor uses very little current, that won't be a problem.

I am using an IMU sensor and an NRF radio. They both run on 3.3v.

A (fake) nRF24L01+ ? I think they require not a large amount of current (only 10mA or 20mA or so), but I'm not sure. I will probably work.

The 3.3v is regulated and will always output 3.3v if the device is powered on.


text:
Writing a new function: configMotor(speed, direction)
How can I create a function that can control a DC motor's speed and direction?
configMotor(int speed, direction){
   pwmVal = speed;

   //need help with code for picking direction
}

//move FORWARD
void moveForward(){
  analogWrite(pwn, pwmVal);
  delay(sDelay);
  digitalWrite(ina, HIGH);
  digitalWrite(inb, LOW);
}

//move BACKWARD
void moveBackward(){
  analogWrite(pwn, pwmVal);
  delay(sDelay);
  digitalWrite(ina, LOW);
  digitalWrite(inb, HIGH);
}

I don't know what to write in the code for configMotor function so that it can choose going forward or backward.

All you need to do is pass a parameter to config that says forward or backwards (was direction).
This parameter then sets the values of that the pins INA/B will be set to, because they are opposite.
Does that make sense?  If not add a comment with you question and I'll try and clarify.
int inaDirection = LOW;
int inbDirection = LOW;

void configMotor( int speed, bool forwards = true)
{
   pwmVal = speed;
   inaDirection = forwards?HIGH:LOW;   // ? and : are the same as an if statement, just more compact.
   inbDirection = forwards?LOW:HIGH;
}

// move no need for forward and reverse anymore
void move()
{
    analogWrite(pwn, pwmVal);
    delay(sDelay);
    digitalWrite(ina, inaDirection);
    digitalWrite(inb, inbDirection);
}

why is bool forwards set to equal to true in the parameter declaration?

bool forwards = true means by default the function should go forwards.  You can call configMotor(40); or configMotor(40, true);they both mean the same thing, where asconfigMotor(40, false);` means go backwards.  I added the default value to make it clearer to you that true meant forwards, I guess it didn't work :)


text:
Arduino continuously reading ADC value using interrupt
I have a mono jack audio act as analog input for arduino UNO. The microphone outputs voltage that varies in terms of amplitude (volume) and frequency. In order to get the high sampling rate, I use prescaler 16 and set high baudrate for serial communication to print the value. I save the analog read from that jack audio to buffer array with maximum value is 256 (8-bit). This is my code (I modify from the Nick Gammon's blog about ADC here) :
const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

void setup ()
  {
  Serial.begin (230400);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
//  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

}

// ADC complete ISR
ISR (ADC_vect)
{
    results[resultNumber++] = ADC;
    if(resultNumber == MAX_RESULTS)
    {
      ADCSRA = 0;  // turn off ADC
    }
}

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void loop () {

  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.println (results [i]);
  }
}

With that code, I got a nice result of sinusoidal graph represented audio value up to 4000 Hz like this :

But one thing that didn't work is if I change the volume or frequency (while displaying data) of analog input (jack audio), the graph I print and display via serial plot audio won't change. So I had to close it and open again to see the change. The question is how can I achieve the continuous and real time reading of this ? Thank you very much.

reset the resultNumber to 0 after you have written it to serial. and turn interrupts back on
void loop () {

  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.println (results [i]);
  }
  resultNumber = 0;
  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF)| bit (ADPS2) | bit (ADATE);
   // turn ADC back on
}

Okay I'll try that first


text:
How do I set a continuous servo to turn on until a switch is flicked?

I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.
Here is the schematic:

Here is my code:
#include <Servo.h>
Servo servo1;

int button = 2; //Assigning pin 2 for the momentary button
int buttonval = 0; //Creating a variable for the buttons value
int green = 12;
int red = 13; //Assigning the green and red LED to pin 12 and pin 13
int red = 13;
int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
int Open = 7;
int Closedval = 0; //Creating two blank variables for the states of the switch
int Openval = 0;

void setup() {
  servo1.attach(4); //Assigning the data pin for the servo
  servo1.write(1); // Giving a starting speed to the servo
  pinMode(button, INPUT); // Setting up the input pin for the momentary button
  digitalWrite(button, HIGH); //  turn on pull up resistors
  pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
  pinMode(Open, INPUT);
  pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);
  digitalWrite(Closed, HIGH);
  //Turning on pull up resistors for the two inputs from the toggle switch
  digitalWrite(Open, HIGH);
}

void loop() {
  Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
  Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

  if (Closedval == HIGH) {
    servo1.write(180);
    // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
  }

  if (Openval == HIGH) {
    servo1.write(86);
    // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
  }

  digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
  digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
}

Any help would be appreciated.

I think you need to look into switch debouncing.
Also add some debug statements to ensure the correct things are happening.

Your are not debouncing your input buttons, which means that digitalRead(Closed) (and Open) will be HIGH in one execution of loop and in the next pass, 3 millis later, it will be LOW.
The servo probably need over 50ms to complete the action (you don't said what servo are you using).
You need to wait for the action to be completed before trying to move it in another direction.
You didn't post your schematic, so may be you wired things wrong. How can we know?
Usually the first step when you find a problem is add Serial.print to know what is working and what not, and then correct the problem.

It is a Continuous Servo, I will add some serial print to see what is going on.

I seem to have got this working just by doing the following code:
#include <Servo.h>
Servo servo1;

int green = 12;       //Assinging the green and red LED to pin 12 and pin 13
int red = 13;

int Closed = 8;       //Assinging the Inputs of the toggle switch to 8 and 7

void setup()
{
  servo1.attach(4);    //Assigning the data pin for the servo
  servo1.write(86);     // Giving a starting speed to the servo

  pinMode(Closed, INPUT);        //Setting up the inputs for the two states of the toggle switch

  pinMode(green, OUTPUT);        //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);

  digitalWrite(Closed, HIGH);    //Turning on pull up resistors for the two inputs from the toggle switch

  delay(50);
  servo1.write(65); // start the motor opening
}

void loop() {
  if (digitalRead(Closed) == HIGH) { //If the toggle switch is changed then turn the servo in the oppisite direction
    servo1.write(100);
    if (digitalRead(Closed) == LOW) { // If the toggle switch is changed again then turn the servo off
      servo1.write(86);
    }
  }
}

Instead of using an external button I have had to use the reset button.

Please, tell us how you use the reset button inside your sketch.

Where do you lit up the LEDs?

So for now I have got rid of the LED's but I am gonna add them in again later. Instead of using an external button wired up to activate the sequence of the servo motor, I have decided to have start of the sequence before the void loop () and so when I restart the Arduino using the reset button it will restart the sequence. It seems to work well.


text:
How do I call functions sequentially without using the Delay function?
I've been messing with the Adafruit Neopixel lib, and I'm trying to replace some of the delay functions with mills ( so that I don't block the serial port ). So far I have the following code;
void loop() {
  currentMillis = millis();

  colorWipe(strip.Color(255, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 255, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 255), 50); // Blue
  colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
}

void colorWipe(uint32_t c, uint8_t wait) {
  if (currentMillis - previousMillis >= 200) {
    for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      //delay(wait);
      Serial.println("Light");
      previousMillis = currentMillis;
    }
   Serial.println("Done");
  }
}

The issue I'm running into ( and I do understand this is fundamental concept in Arduino programming ) is how to run sequential functions, like the ones in loop, while still not blocking the main loop. The way this currently functions, it runs through the first colorWhipe loop and then just keeps iterating.

I'm assuming you want to run each colorWipe for 200 ms, one after another.
You need a state machine to timing each colorWipe, like this:
void loop()
{
    static int state = 0;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;

        switch(state) {
        case 0 :
            colorWipe(strip.Color(255, 0, 0), 50); // Red
            state++;
            break;

        case 1 :
            colorWipe(strip.Color(0, 255, 0), 50); // Green
            state++;
            break;

        case 2 :
            colorWipe(strip.Color(0, 0, 255), 50); // Blue
            state++;
            break;

        case 3 :
            colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
            Serial.println("Done");
            state = 0;
        }
    }
}

void colorWipe(uint32_t c, uint8_t wait)
{
    for(uint16_t i=0; i<strip.numPixels(); i++) {
        strip.setPixelColor(i, c);
        strip.show();
        //delay(wait);
        Serial.println("Light");
    }
}

In each loop you will be waiting 200 ms before doing anything. When the times comes, you will enter the if with state==0 and you will execute the first 'colorWipe'. After that, you advance the state by adding 1 to state variable.
Then you will be entering loop and doing nothing for another 200 ms. When that time pass, you will enter the ìf with state==1. Now the second colorWipe will be executed.
When the last colorWipe is executed, you set state to zero and begin again.

Assuming the commented out delay in colorWipe should still happen then you need to nest the state machines:
void loop()
{
    static bool waiting=false;
    static int state = 0;
    static unsigned long previousMillis = 0;
    unsigned long currentMillis = millis();
    if(waiting){
        if(currentMillis - previousMillis >= 200){
            waiting = false;
        }
    }

    if(!waiting  && currentMillis - previousMillis >= 50) {
        previousMillis = currentMillis;

        switch(state) {
        case 0 :
            if(colorWipe(strip.Color(255, 0, 0))){ // Red
                state++;
                waiting = true;
            }
            break;

        case 1 :
            if(colorWipe(strip.Color(0, 255, 0))){ // Green
                state++;
                waiting = true;
            }
            break;

        case 2 :
            if(colorWipe(strip.Color(0, 0, 255))){ // Blue
                state++;
                waiting = true;
            }
            break;

        case 3 :
            if(colorWipe(strip.Color(0, 0, 0, 255))){ // White RGBW
                state++;
                state = 0;
            }
            break;
        }
    }
}

int wipeState = 0;
bool colorWipe(uint32_t c)
{

    strip.setPixelColor(wipeState , c);
    strip.show();

    Serial.println("Light");
    wipeState++;
    if(wipeState == strip.numPixels()){
        wipeState = 0;
        return true;
    }
    return false;
}

Here's an OOP solution. (It seems a lot of Arduino programmers shy away from C++ classes, but I use them all the time).
Since you don't want to block loop(), you need to create a function that will set the pixel (if time has expired) and return immediately. I would create a class to encapsulate the pixel strip.
The way this works is the class has a loop() function that needs to be called every time in the main program's loop() function. The class's loop() will either return (almost) immediately or it will update the pixel. Which will also be very quick. This allows you to do other things in the main loop().
Disclaimer: I just whipped this up, there may be bugs.
// A class to encapsulate the neo pixel strip.
class color_strip {
    protected:
    Adafruit_NeoPixel pixels;
    uint32_t last_ms;
    uint32_t color;
    uint32_t duration = 0;
    int current_pixel;
    bool first_time;

    public:
    // Constructor
    color_strip(int num_pixels, int pin) {
        strip = Adafruit_NeoPixel(num_pixels, pin, NEO_GRB + NEO_KHZ800);
    }

    // Call this from setup()
    void setup() {
       strip.begin();
    }

    // Call this to start a wipe
    // param duration_ms is how long the entire wipe should take
    void wipe(RGB color, uint32_t duration_ms) {
        // Calculate how long to light each pixel
        duration = duration_ms / strip.numPixels()
        // Initialize this data for loop()
        last_ms = millis();
        first_time = true;
        this->color = strip.Color(color.red, color.green, color.blue);
        current_pixel = 0;
    }

    void loop() {
        // Is there something to do? Only if duration != 0
        if (0 != duration) {
            // Time to change pixel?
            uint32_t current_ms = millis();
            if (current_ms - last_ms >= duration || first_time) {
                first_time = false;
                // Finished the entire wipe?
                if (current_pixel == strip.numPixels()) {
                    duration = 0;
                }
                else {
                    // Set the pixel
                    strip.setPixelColor(current_pixel++, color);
                    strip.show();
                    // Save
                    last_ms = ms;
                }
            }
        }
    }

    // Returns true if doing a wipe, else false
    bool working() {return duration != 0;}
};

Usage: you can create an array of colors. You then cycle through all these colors. If you want to add more colors, simply add to the array.
// Helper struct to store rgb
struct RGB {
    byte red, green, blue;
};
RGB all_colors[] = {
    {255, 0, 0},
    {0, 255, 0},
    {0, 0, 255},
    {0, 0, 0}
    // Add more colors here, if needed
};
// Need to keep track of the current color being displayed
byte current_color = 0;
const byte num_colors = sizeof(all_colors) / sizeof(all_colors[0]);

// Here's the actual object
// Change the parameters to whatever they need to be in your setup
color_strip strip(number_of_pixels, pin_number);

void setup()
    // Call the class setup function
    strip.setup();
}

void loop()
{
    // If the strip has completed its wipe, set it to next color
    if (!strip.working()) {
        current_color = (current_color + 1) % num_colors;
        strip.wipe(all_colors[current_color], 1000);
    }
    // Call the class loop(). It will return quickly so won't block
    // the rest of the program
    strip.loop();

    // Do other stuff here...
}

Well, the OP have problems with a simple algorithm. I don't think using classes will be the best approach for him. Using C++ produces brain damage.

By adding duration to millis, you introduce the rollover problem.

@LookAlterno Not sure if that's a joke or not....Anyway, OP needs to be able to handle classes. Adafruit_NeoPixel is a C++ class.

@Jot Rollover should not be an issue with unsigned variables. See the answer here: https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover

@JohnnyMopp. I use classes and I wrote them too. C++ i's like an enema, something you have to do, but not mean to be enjoyed.

@JohnnyMopp As far as I know, calculating a time in the future has the rollover problem. I mean this line "last_ms = millis() + duration;". Suppose duration is 10 and millis is 0xFFFFFFFA. Then last_ms will become 4. The next millis() - last_me will return 0xFFFFFFF6, which is larger than duration, but millis() has not even counted to the next millisecond.

@Jot Ok. I thought you were referring to the main loop. I just through that in there to force an update the first time. I've replaced it with a flag. Thanks.