text:
Flash a hex file to an MCU/Arduino over the air?
I have a processor AT328 , Arduino bootloaded, and a Bluetooth on the serial lines Tx,Rx .
I would like to program the chip over Bluetooth, not using a computer or IDE, but mobile phone with my own Hex uploader.
So, if the hex file was just a huge text that you have to send, i would obviously just send it and thats it, as I understand there is a mechanism ?
Question : How exactly a Hex file is sent over serial to program the chip ? is it like any other text file? is there any mechanism I have to write? specific baud rate? is there any article about this ?

with a phone, you can run the "AVR dude" application with STK500 emulation to send the hex file as a serial stream to an arduino chip which as the bootloader on it.

read up on how Arduino initiates the programming operation from the IDE - it literally just passes some data to "AVR dude" which runs on command line in Unix and Windows environments, and i'm sure runs on Android somehow

Do some research  and you'll find that this is either a solved problem, or a combination of individually solved ones, though not without issues that may be of concern.

I did research a lot. There is not even a single solution to this for iOS.

Basically, this is much more involved than it might appear on the surface. If you haven't already, I would make sure that I was comfortable with finding things in the datasheet (and it's a really good datasheet, at that). If you're still up for it, read on.
Bootloader
The way a bootloader works on the ATmega328 is that the memory on the chip is self-modifying. This means you can have a piece of code on the chip that modifies memory on the rest of the chip. A bootloader is one such piece of code that runs when the chip first starts up, and checks to see if there's code to be loaded. If there is, it writes that code to the rest of the memory, and then executes it. See section 12.2 of the datasheet.
The way you would program an actual bootloader is described in detail in section 30 "BTLDR - Boot Loader support". I haven't programmed a bootloader before, so you're on your own here, but there are plenty of resources to guide you. In fact, the datasheet has example code in there for it.
(Note that you must program your chip normally at least once, to put the bootloader on it.)
One thing to note is that bootloaders should be small. You don't want bootloaders to take up a lot of your memory, since they only run once on boot and are really just a convenience feature. There are competitions for writing the smallest/most efficient bootloader, and you'll almost certainly want to write your bootloader in assembly. Notice that the only example code given in the datasheet is in assembly. Which brings me to my next point:
Bluetooth
Bluetooth is very annoying to program for. You have to set up different profiles, or do GATT stuff if your module is actually BLE/"Smart" instead of classic bluetooth, etc. However, I'm assuming from your post that you just have one of those serial modules you can find on eBay for dirt cheap. Before I go on, I want to make this very clear: It is non-trivial to set up. It will take up lots of precious code space on your microcontroller that you would want to use on your actual program. Remember how bootloaders are written in assembly? Writing a bluetooth interface in assembly will probably take a while.
As for how your bluetooth module works; it is basically a serial port, but over-the-air. This means the bluetooth interface that you write would need to bit-bang everything if you don't use the built-in USART (say you need those pins for your actual program), and if you do use the built-in USART, setting that up will take even more time. (For a guide on how to setup the USART, see section 24 of the aforementioned datasheet. See? It's really handy.)
Once you actually have bluetooth working, you can do whatever you want. Since you write the bootloader, you can read data from your bluetooth serial link however you fancy. As long as you know what you're sending, all you have to do is read it back accordingly.
Bonus: Flashing
You are correct that a .hex file is just a huge text file that you send to the chip. However, the way the ATmega is actually programmed is not simply using the serial port; instead, it's a slightly extended SPI protocol. (If you don't know what SPI is, you really shouldn't be doing this. If you're curious, Sparkfun has a nice tutorial on SPI.) This is called ICSP, or "in-circuit serial programming". The way to do this for AVRs is explained in an application note.
Of course, you cannot replicate this with just a bluetooth module. Instead, you would need a co-processor to program your chip for you, and read the data to-be-programmed from your bluetooth module.

TL;DR: This is probably not worth it. If you're planning on doing this, it will take significant resources, and you might even need a better chip to get anything done. You almost certainly should just buy an ESP8266 / ESP32 instead.

It is indeed a complex subject, but I believe if you look around you'll find the flashing Arduino type devices via a bluetooth module talking to the (or at least a) bootloader is a demonstrated capability, though I'm not sure I'd want to rely on it in comparison to a more thought-through OTA scheme.

@Ernest3.14 Thanks, you assume too many things, I think I know what SPI is because I am on my way to the third electrical engineering degree. I do not use a cheap module but a very good chip from a large company, and using ESP is pretty stupid, I don't even have enough space to start explaining why.

Awesome, I wasn't sure so I put it in just to be safe :P


text:
Programming an AVR using ISP
I am trying to program an atmega with arduino sketch using ISP only (mac user).
So I know how to burn a boot loader, and then to program the chip using the TX, RX. But I would like to program it directly using ISP, without a boot loader.
So I am using the UNO as a ISP programmer, and trying without success to program a chip on a PCB:

I upload to the UNO the ArduinoISP sketch
Connect the lines to the target board (target board have atmega328, crystal, capacitors, LED)
Choose the board "Arduino pro or pro mini" in the Arduino IDE.
Choose the programmer- "Arduino as ISP"
At the beginning I tried to upload a boot loader, to see if its going well, it DID boot loaded the chip,so I know the connections are good, and I am set to go.

Now, I am trying to just upload a sketch using the SAME ISP connection, I didn't touch anything(!) , so I opened the blinking example, hit the upload button, and it's just not working (not in sync).
Again, the goal is now to program a chip with ISP directly, without a boot loader. The reason I boot loaded it is to see it's all connected well.
I can't imagine how the exact same configuration can bootload the chip,and later can't upload a sketch directly using the ISP.
What am I missing here? Can't you use the Arduino IDE to upload a sketch directly as an ISP programmer?

i have one , and have the same problem!

Agreed, this is off-topic for EESE.  But FWIW, what you're doing should of course be possible (program the device with just your sketch & no bootloader), and the fact that you can burn just a bootloader but not the sketch might mean your electrical connections are ok, so my next suggestion would be to confirm that your target hardware is in fact a Pro or Pro-Mini or very compatible to it. Fuse settings of course vary from one platform to another...

Uploading the bootloader probably changed the fuse settings. Try connecting a crystal to the chip.

Are you clicking "File>Upload using programmer" to upload?

These details may help if you already have not checked: https://docs.arduino.cc/built-in-examples/arduino-isp/ArduinoISP/

You probably used a direct upload button that uses default Arduino programming using RX TX, not the programmer you had selected.
All wirings are perfect that's why you were able to burn the bootloader.
Now you just need to go under Sketch -> Upload Using Programmer.

source: Stack Exchange

license: 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/

sort: votes


text:
Put ATmega328 in very deep sleep and listen to serial?
I have investigated the sleeps options of the ATmega328, and read a few articles about it, and I would like to understand if there are more options.
So I would like to get as low current as possible, so that anything less that 100uA would be good - as long as I can listen to uart and interrupts for waking up.
I am using a custom PCB (not the UNO), with ATmega328p.
Setting the chip to deep sleep:
 set_sleep_mode (SLEEP_MODE_PWR_DOWN);
 sleep_enable();
 sleep_cpu ();

would not wake it up with serial communication,according to this.
You will need to put it in IDLE mode, to listen to serial, but this would consume a few mA -bad.
I have found this link where you can connect in hardware the serial to the interrupt - which is dangerous so you can loose data, and moreover, I need these 2 interrupts pins.
I also read this article of Gammon, where you can disable some things, so you can get IDLE sleep with much lower power - but he didn't mention how exactly you get from this:
 power_adc_disable();
      power_spi_disable();
      power_timer0_disable();
      power_timer1_disable();
      power_timer2_disable();
      power_twi_disable();

So, bottom line, is there any option out there, to get less than 0.25mA at least, and also listen to serial port, without any hardware manipulation?
For example, waking up with long serial data input?

@NickAlexeev this is an ATmega328 question not an Arduino one as it is deals directly with the chip far below the level of Arduino.  Stop with the improper migrations already!

Hardly. Wanting to wake an Arduino from sleep can't really be dismissed because it has an ATmega328 chip in it. At that rate you'll be able to bounce all the question about Arduinos back to the EE site.

A board we make does this.

The RX pin is wired to INT0
INT0 pin set to input or input pullup depending on how the RX line is driven
On sleep, INT0 low level interrupt is enabled
//Clear software flag for rx interrupt
rx_interrupt_flag = 0;
//Clear hardware flag for rx interrupt
EIFR = _BV(INTF0);
//Re-attach interrupt 0
attachInterrupt(INT_RX, rx_interrupt, HIGH);

INT0 interrupt service routine sets a flag and disables the interrupt
void rx_interrupt()
{
    detachInterrupt(INT_RX);
    rx_interrupt_flag = 1;
}

On wakeup, we check for the flag (there are other interrupt sources)

On the comms side of things we use a message protocol that has a start character > and end character \r. e.g. >setrtc,2015,07,05,20,58,09\r. This give some basic protection against losing messages, as incoming characters are not processed until a > is received. To wake up the device we send a dummy message before transmission. A single character would do it, but we send >wakeup\r hehe.
The device stays awake for 30 seconds after the last message is received in case of new messages. If a new message is receive the 30 second timer is reset. The PC interface software sends a dummy message every second to keep the device awake while the user has it connected for configuration etc.
This method gives absolutely no problems at all. The board with a few peripherals uses about 40uA when sleeping. The actual current consumed by the ATMega328P is probably around 4uA.
Update
At look at the datasheet shows that the RX pin is also pin change interrupt pin 16 (PCINT16)
Thus another method without wires may be

Before sleep: Set the port change interrupt mask bit in PCMSK2 for PCINT16, clear the pin change port 2 flag in PCIFR, enable the pin change port 2 interrupt (PCINT16-PCINT23) by setting PCIE2 in PCICR.
Setup an ISR for the pin change port 2 interrupt and continue as before.

The only caveat with the port change interrupt is that the interrupt is shared across all the 8 pins that are enabled for that port. So if you have more than one pin change enabled for the port, you have to determine which triggered the interrupt in the ISR. This is not a problem if you are not using any other pin change interrupts on that port (PCINT16-PCINT23 in this case)
Ideally this is how I would have designed our board but what we have works.

Thanks very much . Is there no other way than hardware tricks??? So you only connect rx to int0/int1 with 1 line ??

Actually I just had a look at the data sheet and you might be able to use a pin change interrupt

Thanks,what would be the different? Anyway i would have to wake up with rx on int1?

You only need 1 interrupt pin. I posted some more above - you could use the RX pin as a pin change interrupt. I haven't done this though so there might be a few catches like maybe you will have to disable RX / enable pin change before sleep and disable pin change / enable RX after wakeup

thanks, i am not sure why should be a problem with just connecting rx to INT1,set the to interrupt on high ,than disable interrupts when int1 happens, and enabling them again when go to sleep ?

Yep sounds good. The pin change way I just put there in case you couldn't make the mod on the board. IIRC the MCU has to generate a clock source for the UART subsystem, which is probably why it is one of the first systems to be disabled as the sleep level is increased. This is why you can only do deep sleep and UART with interrupts.

ok great thanks, so you trust this configuration on mass production ? :))

also should you put on the int1 pin a pulldown/up ?

I think using a pin change interrupt as in Nick's answer is the most elegant solution. When I first was making the board I mistakenly thought only INT0 and INT1 worked in sleep mode. (Note 3 under the sleep mode table seemed to imply this)

As for production either method should work fine. We've never had a problem. On our board an RTC wakes the atmega328p up every 0.5s on INT1 and that has never failed.

INT1 pin as a pullup (atmega328p can do this internally) if for any reason the pin will be left floating. The default state of UART pins is VCC when there is no activity so the pullup wont consume any current.

The code below achieves what you are asking:
#include <avr/sleep.h>
#include <avr/power.h>

const byte AWAKE_LED = 8;
const byte GREEN_LED = 9;
const unsigned long WAIT_TIME = 5000;

ISR (PCINT2_vect)
{
  // handle pin change interrupt for D0 to D7 here
}  // end of PCINT2_vect

void setup()
{
  pinMode (GREEN_LED, OUTPUT);
  pinMode (AWAKE_LED, OUTPUT);
  digitalWrite (AWAKE_LED, HIGH);
  Serial.begin (9600);
} // end of setup

unsigned long lastSleep;

void loop()
{
  if (millis () - lastSleep >= WAIT_TIME)
  {
    lastSleep = millis ();

    noInterrupts ();

    byte old_ADCSRA = ADCSRA;
    // disable ADC
    ADCSRA = 0;
    // pin change interrupt (example for D0)
    PCMSK2 |= bit (PCINT16); // want pin 0
    PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7

    set_sleep_mode (SLEEP_MODE_PWR_DOWN);
    power_adc_disable();
    power_spi_disable();
    power_timer0_disable();
    power_timer1_disable();
    power_timer2_disable();
    power_twi_disable();

    UCSR0B &= ~bit (RXEN0);  // disable receiver
    UCSR0B &= ~bit (TXEN0);  // disable transmitter

    sleep_enable();
    digitalWrite (AWAKE_LED, LOW);
    interrupts ();
    sleep_cpu ();
    digitalWrite (AWAKE_LED, HIGH);
    sleep_disable();
    power_all_enable();

    ADCSRA = old_ADCSRA;
    PCICR  &= ~bit (PCIE2);   // disable pin change interrupts for D0 to D7
    UCSR0B |= bit (RXEN0);  // enable receiver
    UCSR0B |= bit (TXEN0);  // enable transmitter
  }  // end of time to sleep

  if (Serial.available () > 0)
  {
    byte flashes = Serial.read () - '0';
    if (flashes > 0 && flashes < 10)
      {
      // flash LED x times
      for (byte i = 0; i < flashes; i++)
        {
        digitalWrite (GREEN_LED, HIGH);
        delay (200);
        digitalWrite (GREEN_LED, LOW);
        delay (200);
        }
      }
  }  // end of if

}  // end of loop

I used a pin-change interrupt on the Rx pin to notice when serial data arrives. In this test the board goes to sleep if there is no activity after 5 seconds (the "awake" LED goes out). Incoming serial data causes the pin-change interrupt to wake the board. It looks for a number and flashes the "green" LED that number of times.
Measured current
Running at 5 V, I measured about 120 nA of current when asleep (0.120 µA).
Awakening message
A problem however is that the first arriving byte is lost due to the fact that the serial hardware expects a falling level on Rx (the start bit) which has already arrived by the time it is fully awake.
I suggest (as in geometrikal's answer) that you first send an "awake" message, and then pause for a short time. The pause is to make sure the hardware does not interpret the next byte as part of the awake message. After that it should work fine.

Since this uses a pin-change interrupt no other hardware is required.

Amended version using SoftwareSerial
The version below successfully processes the first byte received on serial. It  does this by:

Using SoftwareSerial which uses pin-change interrupts. The interrupt which is caused by the start bit of the first serial byte also wakes the processor.
Setting the fuses so that we use:

Internal RC oscillator
BOD disabled
The fuses were: Low: 0xD2, High: 0xDF, Extended: 0xFF

Inspired by FarO in a comment, this lets the processor wake up in 6 clock cycles (750 ns). At 9600 baud each bit time is 1/9600 (104.2 µs) so the extra delay is insignificant.
#include <avr/sleep.h>
#include <avr/power.h>
#include <SoftwareSerial.h>

const byte AWAKE_LED = 8;
const byte GREEN_LED = 9;
const unsigned long WAIT_TIME = 5000;
const byte RX_PIN = 4;
const byte TX_PIN = 5;

SoftwareSerial mySerial(RX_PIN, TX_PIN); // RX, TX

void setup()
{
  pinMode (GREEN_LED, OUTPUT);
  pinMode (AWAKE_LED, OUTPUT);
  digitalWrite (AWAKE_LED, HIGH);
  mySerial.begin(9600);
} // end of setup

unsigned long lastSleep;

void loop()
{
  if (millis () - lastSleep >= WAIT_TIME)
  {
    lastSleep = millis ();

    noInterrupts ();

    byte old_ADCSRA = ADCSRA;
    // disable ADC
    ADCSRA = 0;

    set_sleep_mode (SLEEP_MODE_PWR_DOWN);
    power_adc_disable();
    power_spi_disable();
    power_timer0_disable();
    power_timer1_disable();
    power_timer2_disable();
    power_twi_disable();

    sleep_enable();
    digitalWrite (AWAKE_LED, LOW);
    interrupts ();
    sleep_cpu ();
    digitalWrite (AWAKE_LED, HIGH);
    sleep_disable();
    power_all_enable();

    ADCSRA = old_ADCSRA;
  }  // end of time to sleep

  if (mySerial.available () > 0)
  {
    byte flashes = mySerial.read () - '0';
    if (flashes > 0 && flashes < 10)
      {
      // flash LED x times
      for (byte i = 0; i < flashes; i++)
        {
        digitalWrite (GREEN_LED, HIGH);
        delay (200);
        digitalWrite (GREEN_LED, LOW);
        delay (200);
        }
      }
  }  // end of if

}  // end of loop

Power consumption when asleep was measured as 260 nA (0.260 µA) so that is very low consumption when not needed.
Note that with the fuses set like that, the processor runs at 8 MHz. Thus you need to tell the IDE about that (eg. select "Lilypad" as the board type). That way the delays and SoftwareSerial will work at the correct speed.

@NickGammon thanks a lot ! i did it already and it worked . Is that way is common in other products that we use everyday, or they have other ways to listen to comm and sleep ? (all MCU's cant listen to uart at deep sleep?)

I was reading the datasheet and it states that when using internal oscillator, only 14 clock cycles are needed to start the chip, provided that BOD is used. If the power source is always up (batteries), that could be used also without BOD? violating the specs of course. That would bring the chip up very shortly after the incoming UART edge, but still I'm not sure it would be enough to catch the first byte.

Yes, 14 clock cycles isn't long, however possibly the UART would still miss the edge (after all, the edge is when the processor notices the change). So even if it starts up very soon after the edge it might still miss it.

A bit of testing indicates that (even with BOD enabled) it doesn't work. The processor needs to be awake to notice the leading edge (start bit) and thus powering it up after receiving it (even if very shortly after) doesn't work.

The 14 clock cycles are after reset. You only need 6 cycles after power-down, if you use the internal RC oscillator. See additional example code.

I saw the amendment. Amazing job, as usual.

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


text:
Producing a sine wave with the DAC?
Its being a few days i am trying to achieve something that I dont really know if possible.
Using the Samd21 chip(Arduino Zero), I am using a timer and a DAC to produce a sine wave.
The required frequencies are 100Khz to 3Mhz. I know its sounds too much, but according to my calculations its possible- I would like to know if I am wrong with my software approach.
Pseudo is this :
1.I create a look-up table of a sine wave = array of a sine samples that holds N samples
2.I use a timer with a pre scale of 1, where the clock speed is 48Mhz
3.Each timer tick I produce from the DAC 1 sample from the sine wave
4.To change frequencies I am changing the timer top counter value.
If we try to speak about the max frequency, according to Nyquist , a 3MHz sine must be sampled with at least 6MHz sample rate, and my sine array has 15 samples, means 45Mhz sampling rate.(=good)
Then the sine frequency is :
sineF= TimerF*sineSamples = TimerF*15

Than means I need a timer frequency of :
TimerF=15*sineF = 15*3Mhz=45MHz

So, both are good, the timer max f can be 45Mhz, and the sampling rate is good according to Nyquist.
The only concern here, is if the DAC can do that(speed), and if changing the timer frequency fast enough (even every period) is acceptable.
Is this whole software approach true ?
If its not, producing a square wave probably possible,since it requires much less speed, but then, can you turn it into a nice clean sin wave with filters?
Thanks.

First, I have to say I am not familiar with the Zero hardware, so I am
answering in quite general terms. Hopefully you will also get some
answers with hardware-specific information. That being said, here are my
first thoughts:

Your approach seems reasonable to me, but you are too optimistic
regarding the achievable sampling rate.
DACs are usually fast. It's unlikely that the DAC will limit the
frequency you can achieve.
You cannot achieve a sampling frequency of 45 MHz in software
with a CPU running at 48 MHz: your code to output a sample would
have to run in less than 1.07 CPU cycles.
You may achieve a higher sampling rate with an array of
16 samples rather than 15, as wrapping the array index modulo 16
can be optimized by the compiler into a bitwise AND, which is likely to
be faster than computing index%15.
Fastest would probably be to use a busy loop with constant execution
time and interrupts turned off (I know how to do that on AVR, but not on
ARM). Problem is: the program cannot do anything else than outputting
samples.

Thanks a lot, I think that DAC's are really slowly, I could see that other DAC's of ARM's such as the Due, are capable of max 1MHz rate. And regarding to your assumption on the sampling frequency of 48MHz, you can definitely do that, a pre scale 1 for a timer provide it with a processor clock speed, and if you count to 1( timer counter 1 cycle) you do get a 48MHz, this is how it works with any frequency , so I am not sure you assumptions are correct.

The problem is not triggering the timer fast enough, it's having any time between triggerings of the timer to actually retrieve the sample from the LUT and send it to the DAC. There just isn't any time.

Ok, I have checked it out, DAC is too slow! its 350ksps, that means 350Khz, so it IS a limit. Regarding the timer you are right. So I can just put it on 16Mhz, or something similar(?)

You have to allow enough time for the instructions you are executing to run. That means, effectively, one clock cycle for each and every assembly (NOT C) instruction. That could be hundreds of clock cycles - maybe thousands - depending on just what you are doing in your interrupt routine.  I am not familiar with that chip, but if it has DMA that would be a more efficient way of doing it.


text:
Record video with CMOS camera using Arduino
Is it possible to use this with Arduino to record and store videos on memory card?
Additionally, if someone has already done it, a tutorial link would be appreciated.

Arduinos have two major drawbacks:

Not enough memory.
Way too slow.

There's a shield to help you do that:
http://nootropicdesign.com/ve/
http://blog.arduino.cc/2011/03/24/arduino-computer-vision-with-video-experimenter-shield/

Some more info from electronics.stackexchange: http://electronics.stackexchange.com/questions/50576/how-to-stream-arduino-based-camera-to-http-server


text:
Adafruit libary and CC3000 shield
I have a Arduino Uno and a CC3000 shield. When I run the example code for Webclient from Adafruits libary it works perfect.
When I switch out address for reading a corresponding text file from my own server the code completes sporadically. The output in the serial window stops at differens places every time.
Does anyone have any idea how I can fix this?
The Adafruit points to this URL: http://www.adafruit.com/testwifi/index.html
While mine points to this URL: http://a.sjsd.li/test/test.html

Can you show the results you got? All your test page contains is 'hello world' so there should be no problems reading it from the server. What HTTP response do you get?

The response header it HTTP/1.1 200 OK, here you got an example of failure:

HTTP/1.1 200 OK
Server: Apache
Last-Modified: Sat, 16 Jan 2016 11:38:42 GMT
ETag: "c98e4d75-c-52971f630f480"
Vary: Accept-Encoding
Content-Type: text/html
Transfer-Encoding: chunked
Date: Sat, 16 Jan 2016 18:06:16 GMT
X-Varnish: 1632177268 1632051084
Age: 71
Via: 1.1 varnish
Conn

Edit your post to include the response PROPERLY FORMATTED, so we can know what's missing. Is this result consistent? Does the response always cut off at this point?

Please edit your post to include the additional information requested. Select it and hit Ctrl+K to make it monospaced formatting.

Sorry for the bad formating of the code guys. It seems like I can't make it to work. Ctrl + K makes the foucs jumpt to the URL-field in Chrome.
@brianrho No, sometimes it doesen't get this far.

I have arrived at a solution that works for me. Instead of using Adafruit library I have adopted Sparkfuns library.
Some adjustments in the setup for the pins:
#define CC3000_INT      3   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       5   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno
#define SD_CS           4   // Chip select for SD card

Then some adjustemnt in the block for the HTTP request:
client.print("GET /index.html HTTP/1.1\r\n");
client.print("Host: ");
client.print(server);
client.print("\r\n\r\n");
client.println();
Serial.println();

This is not a solution for the Adafruit libary. But it helped me to continue my project.

Perhaps the CC3000 isn't waiting long enough for the whole response to come in. Try increasing the variable IDLE_TIMEOUT in the Web_Client sketch, near the top. Change its value to 10000 and see if you get the whole response this time.

I have tried to to change the value. But it doesen't help at all.


text:
Atlas Scientific pH project - serialEvent3 problems
I am trying to get this pH project working and I've noticed that the serialEvent3 never sets the boolean value sensor_string_complete to true.  I am not sure if it is actually capturing the values from the probe.  What I want is for every loop through it should grab a pH value and that is not happening right now.  Most times through the loop the serial3 port is not providing any values.  Here is my code:
String sensorstring = "";
boolean sensor_string_complete = false;
float pH;

void setup() {
  Serial.begin(38400);
  Serial3.begin(38400); // pH stamp
}

void serialEvent3() {                                 //if the hardware       serial port_3 receives a char
  sensorstring = Serial3.readStringUntil(13);         //read the string until we see a <CR>
  sensor_string_complete = true;                      //set the flag used to tell if we have received a completed string from the PC
}

void loop() {
  getPh();
  if (sensor_string_complete == true) readph();
}

void getPh() {
  Serial.println("we are here");
  Serial3.print("r");
  Serial3.print(13);
}

void readph(){
  Serial.println("read ph here");
  if (isdigit(sensorstring[0])) {
    pH = sensorstring.toFloat();
    Serial.println(pH);
  }
  else{
    Serial.println(sensorstring);
  }

  sensorstring = "";
  sensor_string_complete = false;
}

This returns values such as
we are here
we are here
we are here
read ph here
7.0
we are here
read ph here
7.0
we are here
we are here
we are here
read ph here
7.0
I want this to return these values every loop.  I expect to see:
We are here
read ph here
7.0
We are here
read ph here
7.0
Any help on this would be great.  Thanks so much!

On a typical Arduino, the delay between loop() ending and loop() running again is a few microseconds.  Serial.println() in getPh() is interrupt-driven so that call too takes only a few microseconds.  Writing two bytes with Serial3.print() at 38400 bps will take about half a millisecond.  In short, there is plenty of time for loop() to run several times before  serialEvent3() sets sensor_string_complete.
To call  getPh() once and readph() once per loop(), instead of
if (sensor_string_complete == true) readph();

say
while (!sensor_string_complete) {}
readph();

This will stall the loop while the pH sensor takes and reports a reading.
Note, in getPh() instead of using two separate Serial3.print() statements, you can just say Serial3.print("r\r").


text:
Shared Memory using SHM Library
I am trying to read sensor data from a FIFO buffer embedded in the sensor (LSM9DS1), and store that data on a Teensy 3.2 board to later be put in a file. I can only read 6 bytes at a time from the FIFO.
The sensor's FIFO is read by the Teensy when an interrupt triggers an isr function. I want to store the data on the Teensy memory. Then, after the ISR store the memory, I plan to parse the data and do a few simple calculations in the loop() function before writing it to file.
What is the best way to accomplish this? I tried using a FIFO library for Arduino here, but it doesn't work with interrupts. I encountered errors with declaring it as a volatile memory type.
Could I used shared memory using the sys/shm.h library from C++? If so, how can I import this to my arduino code?

Shared memory?? All the memory is already shared, so just declare it as volatile (so the compiler does not "optimize" access to this variable) and you are done. Instead of using an external library, just write a circular buffer with a fixed size array (one array and two indices or pointers). Remember that with microcontrollers you should follow the KISS principle

Hi frarugi. You're right, the data is shared. My idea with the shared memory was that by I could lock and release the variable as needed so that only one process, either the loop() or isr function, would be able to write/read at a time. I'm not sure if this will be a problem if I use a volatile object.

Well Alex, there is no such thing as "two processes", because that implies that there is a sort of scheduler. You won't have concurrent access, because you always know who is executing: if the ISR is working, then the ISR is executing, otherwise the loop. and you can't "pause" the ISR waiting for the loop to release the lock, because the uC won't execute the loop if it is in the isr. You just have to declare the variable as volatile, since it can be modified in the isr (and so in the loop the compiler can't save it to a register, since it can be modified in any moment)

@frarugi87 Thanks, that clarifies things for me :)

Shared memory only makes any sense in two combined situations:

You have a kernel arbitrating processes, threads and memory allocation, with process isolation
You have multiple threads or processes in your application

You certainly don't have number 1 unless you can install an operating system on the Teensy 3.1 (some RTOS may provide a SHM analogue).
As for 2 yes, it could be said you have two threads. But you don't have any form of process isolation, so what one "thread" can access the other "thread" can access.
Both the ISR and the loop() function have access to the exact same memory. Any global variables are accessible to both. You may need to inform the compiler that a variable is modified in one thread and read in another though. The simplest way of doing that is to make the variable volatile by prepending the volatile keyword to the definition.

Thanks Majenko.  I have a question about using volatile variables. What will happen to this variable if I am, say, in the middle of reading/deleting one entry, then the ISR is called. Then I will try to write new data into the volatile variable. Will this create any problems? This was one thing I was warned about when programming this.

It depends a) what the variable is, and b) what you are doing to it. You can google the phrase "Critical Sections" for ways around any problems that may arise. If your operations are atomic then there can be no problem. If they aren't they can be made atomic by making wrapping them in code to make them atomic, and there's a myriad of ways of doing that.

Thanks for the suggestion, seems to be just the right topic

@Majenko how can you make, for instance, a write to a int32_t atomic? I mean, they are at least four write instructions (and maybe shifts or counter increment). What if the ISR needs to be fired in the middle of this (and of course it needs to change the value of that int32_t )? You can't delay an ISR, so either you throw away the whole ISR (thus losing data) or you will have corrupted data. The solution can be not to work in the ISR (or at least limit the operations in the ISR only to 8 bit data)

@frarugi87 If you are writing to the same value in the ISR and outside the ISR I have to ask one simple question: why?! I can't think of a situation where you would actually want to do that. Read from it outside and write to it inside the ISR maybe, yes. The only safe way is to stop the interrupt firing for the few instructions it takes to read the value from memory into another variable. Keep that critical section as short as possible. If your ISR is firing so fast that you lose data as opposed to just delay the ISR by a few clock cycles then you are doing something wrong.

@Majenko that was a purely theoretical question, because if you have one producer and one consumer you won't have concurrency problems. For instance: you have an int (2 bytes) index in an array. You iterate over it, and in the isr you reset it. now, you are in the middle of a +1 operation (0x0122 to 0x0123). Let's suppose the compiler writes the first byte first. so it writes 0x01 to the first cell, then the ISR comes and writes 0x0000 to the variable. The loop resumes, and writes 0x23 to the second cell. Result? 0x0023. The solution is to delay the ISR, so I asked you: how can you do that?

@frarugi87 The simplest way is to make a critical section around your "outside ISR" operation. Easiest method: cli(); ... your operation ... sei();

@Majenko So disable interrupts and then enable them again... Are "pending" interrupts fired after the sei?

Yes. All you do there is disable the response to the interrupt. The interrupt still happens and is still logged. As soon as you enable interrupts again it sees that there are interrupt flags set and triggers the ISRs for them as per normal.

@Majenko Thank you :) did not know that, and I think that in the future it can come handy.. Thank you!


text:
How to program thresholds?
Hello guys (and gals)!
I'm trying to figure out how to program thresholds using my arduino board.
Essentially, to make this as simple as possible, this is what I have going on.
I am sampling a value every one second, I am taking the value and trying to make certain actions occur based on when this value crosses certain thresholds.
The value read every second will be a value between 0-150.
The thresholds will work something like this:
If value crosses over 20 and becomes 20 or higher, do an action.
If value crosses over 20 and becomes 19.9 or less, do a different action.
And then do the same for a threshold at 30, 40, 50, and 65.
I would need to have it so that if it reads a value of 15, and then a second later, reads a value of 23, it does an action. But if it reads 23, and then reads 24 a next, it needs to not do anything because it hasn't crossed over from one threshold to another. I only want an action to perform if a threshold is crossed either by increasing or decreasing past it.
So again, to reiterate;
If first value read is 34, and second is 42, do an action.
If first value is read at 57, and second at 44, do an action.
If first value is 24, and second value is 26, do nothing. (no threshold was crossed)
The next part would be figured out if a threshold was crossed twice, or more, to do that action twice or more times.
Any advice on how to code this?
Thanks in advance.

Store the previous value.

Thanks again for your contributions.
I've gone ahead and decided to go with the following code. Its purpose is to turn vol up or down based on current car MPH. I choose to define brackets that cover a range of values. When one bracket ends, another begins. I've also set the previous bracket to current bracket at the end of each loop so that the application knows where it was previously, so that if it hops above or goes under a defined bracket, it does the desired action.
I've used a random generator to supply the MPH for testing purposes for now and commented out a few things that disturbed the testing process. If you'd like to critique this code to make is better, please let me know.
Note: I've also borrowed some of this code from another individual (Matthew McMillan, http://matthewcmcmillan.blogspot.com) who wanted to figure out how to convert a vehicle speed sensor wire info into MPH. I needed this code in order to make use of the vehicle's speed.
#include <SPI.h>
#include <Wire.h>

const int lightPin = 0;
const int hardwareCounterPin = 5;
const int samplePeriod = 1000; //in milliseconds
const float pulsesPerMile = 4000; // this is pulses per mile for Toyota. Other cars are different.
const float convertMph = pulsesPerMile/3600;
unsigned int count;
float mph;
unsigned int imph;
int roundedMph;
int previousMph;
int prevCount;

// Declare brackets
const int BracketA = 1;
const int BracketB = 2;
const int BracketC = 3;
const int BracketD = 4;
const int BracketE = 5;
const int BracketF = 6;

// Initialize Previous and Current Brackets
int PreviousBracket = 1;
int CurrentBracket = 1;

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

  TCCR1A = 0; //Configure hardware counter
  TCNT1 = 0;  // Reset hardware counter to zero
}

void loop() {

  /////////////////////////////////////////////////////////////
  // This uses the hardware pulse counter on the Arduino.
  // Currently it collects samples for one second.
  //
  bitSet(TCCR1B, CS12); // start counting pulses
  bitSet(TCCR1B, CS11); // Clock on rising edge
  delay(samplePeriod); // Allow pulse counter to collect for samplePeriod
  TCCR1B = 0; // stop counting
  count = TCNT1; // Store the hardware counter in a variable
  TCNT1 = 0;     // Reset hardware counter to zero
  mph = (count/convertMph)*10; // Convert pulse count into mph.
  imph = (unsigned int) mph; // Cast to integer. 10x allows retaining 10th of mph resolution.

  int x = imph / 10;
  int y = imph % 10;

  // Round to whole mile per hour
  //if(y >= 5){
  //  roundedMph = x + 1;
  //}else{
  //  roundedMph = x;
 // }

  //Code to write your own MPH for testing purposes.
  //if (Serial.available() > 0) {
                // read the incoming byte:
               // roundedMph = Serial.read();
               //}

  //If mph is less than 1mph just show 0mph.
  //Readings of 0.9mph or lower are some what erratic and can
  //occasionally be triggered by electrical noise.
  //if(x == 0){
  //  roundedMph = 0;
 // }

  roundedMph = random(1,80);

  // Don't display mph readings that are more than 50 mph higher than the
  // previous reading because it is probably a spurious reading.
  // Accelerating 50mph in one second is rocketship fast so it is probably
  // not real.
  if((roundedMph - previousMph) > 50){
    roundedMph = previousMph;
  }

  //Place the gatherered MPH value into a bracket
  //---------------------------------------------
  if(roundedMph >= 0 && roundedMph < 20) {
   CurrentBracket = BracketA;  //Value1
   Serial.println("I Choose Bracket A");
    }

  if(roundedMph >= 20 && roundedMph < 30) {
   CurrentBracket = BracketB;  //Value2
   Serial.println("I Choose Bracket B");
    }

  if(roundedMph >= 30 && roundedMph < 40) {
   CurrentBracket = BracketC;  //Value3
   Serial.println("I Choose Bracket C");
    }

  if(roundedMph >= 40 && roundedMph < 50) {
   CurrentBracket = BracketD;  //Value4
   Serial.println("I Choose Bracket D");
    }

  if(roundedMph >= 50 && roundedMph < 65) {
   CurrentBracket = BracketE;  //Value5
   Serial.println("I Choose Bracket E");
    }

  if(roundedMph >= 65) {
   CurrentBracket = BracketF;  //Value6
   Serial.println("I Choose Bracket F");
    }

 //Decide if bracket stayed the same, went up, or down.
 //---------------------------------------------------
 if(CurrentBracket == PreviousBracket) {
 //Do Nothing
 Serial.println("Nothing Changed");
 }

if(CurrentBracket > PreviousBracket) {
 //Command for Vol Up
 int VolUp;
 VolUp = CurrentBracket - PreviousBracket;
Serial.println("Volume Went Up One by ");
Serial.println(VolUp);
delay(2000); // Delay to not change Vol to fast if near threshold
}

if(CurrentBracket < PreviousBracket) {
  //Command for Vol Down
  int VolDown;
  VolDown = PreviousBracket - CurrentBracket;
 Serial.println("Volume Went Down One by ");
 Serial.println(VolDown);
 delay(2000); // Delay to not change Vol to fast if near threshold
 }
  previousMph = roundedMph; // Set previousMph for use in next loop.
  PreviousBracket = CurrentBracket; //Set PreviousBracket for use in next loop.
}

The way you described it, the first and good solution I can approach it is state machine.
You have a lot of thresholds to check and very specific details such as going up at some level and doing something or nothing depending on the level.
What I advise you is creating the state machine for you code setting up all the thresholds and saving the actual state of your system into a variable. After you have this set up, coding is just a matter of switch/cases or if statements.
For example. The first part is to check if it goes until 20 and then keep with at least 20.
switch (state) {
    case 1:
        if (value >= 20 && value < 30)
             state = 2;
        break;
     case 2:
        if (value < 20)
             state = 1;  // initial state
        else if (value >= 20 && value < 30)
             state = 3; // or call a function
        break;
     case 3:
          doSomething();
          break;
}

And you could have some delay or timer interrupt to check the value each 1s and repeat the state machine again and again. If you change or read the value inside an interrupt function call, make sure you declare the variable as volatile otherwise the compiler will optimize it and your machine won't work properly.
This way you can expand the idea and have all the thresholds set up.

That code is faulty – as it stands, once the state changes to 3, it stays at 3 no matter what value occurs.  Also, when state is 1, a value of 30 or more doesn't get processed.  So for example the sequence 15, 35, 15 results in no actions occurring.

Good point, @jwpat. Well, inside the function doSomething, there could be a verification and then decide which state to go in sequence. This code is just a start point where someone could develop their own code. The user has to make sure it checks every single situation to make sure it'll work properly.

It's always a good idea to add a Serial.print() and else/default to be notified via serial if any values go over/under your radar, especially as a beginner.


text:
Is it safe to feed 5v dc 1amp to an Arduino uno R3 board?
Is it safe to feed 5v dc 1amp to an Arduino uno board?

Yes, it is safe.

That's a common newbie question: "What will happen when I use a 1 A power supply for a device which only needs 0.1 A?"
The device will only draw the current it needs. It's the same as on your electricity grid. The nuclear power plant can supply a gigawatt, yet the bulb will only draw the 60 W it needs.
But do you want to apply that 5 V to the power connector? Then the 5 V is too low, you'll need at least something like 6.5 V, otherwise the onboard voltage regulator won't have enough headroom to output 5 V. If you're using the USB connector for a regulated(!) 5 V, then the onboard regulator will be bypassed. Never place an unregulated 5 V on the USB connector, though.

Yes as long as the polarity is correct, the board will only take the current it requires

The 1 Ampère you're mentioning is likely the maximum rating of the power supply, i.e. it cannot sustain higher currents for a long time. However, if you connect your Arduino board (or any other device) to your power supply, the actually flowing current will depend on the voltage U and the resistance R of the device as I = U/R. You can think of this as the Arduino drawing as much power as it needs.
In other words: you must not exceed the maximum voltage, but you don't have to (and cannot in a simple way) adjust the current flowing into the Arduino.


text:
AC ceiling fan speed control using arduino Uno R3
How can I control an AC ceiling fan speed using Arduino Uno R3? I cannot understand the key behind controlling AC voltage using Arduino (though I know how to on/off ac appliances using arduino and relays).

Controlling the speed of an AC motor is not an easy undertaking, and messing around with mains voltages if you're not experienced and know what you're doing can be fatal.
Now that's the disclaimer out of the way, on to your question.
Unlike DC, you cannot use PWM to control the average power of AC.  That is, after all, what PWM does - the on-off ratio creates a percentage of the power - but it can only be done if the incoming power is of a steady state.
For AC there are two ways of reducing the output power - either reduce the voltage, which can be done with resistors (look inside a multi-speed fan and you'll see resistors to change the speed); or chop up the AC waveform, which is a little like PWM but more specialized.
If you only want specific speeds then you could pre-define them using resistors and switch different resistor combinations in and out using relays.  It's crude, but simple, and also probably the safest option for the beginner.
If you want proper variable speed, though, then you're going to have to chop up the waveform.  The theory is quite simple:  Start where the waveform crosses 0V in either direction, with the output on, and turn it off again at some percentage of the way through the cycle.
Like PWM it's the on-off percentage that defines the output power (and thus the speed), but timing is critical - you must start the PWM sequence at 0V and it must last exactly one cycle.

A number of simple circuits work in the opposite way - they remain off until the input waveform reaches a certain point, then switch on, until they reach the zero-crossing point.  While simple, these circuits aren't good.  The reason being that the sudden rise from 0V to the "trigger" voltage when the output becomes live can cause large spikes and noise in the circuit, which can cause lights to blow etc.  It's the same effect as why bulbs most often blow when you turn them on, not when they have been running for a while - it's that very rapid rise from 0V to a high voltage which causes them to be over-stressed and blow.
So any circuit you choose should really be a proper one which turns on at 0V and turns off after a period, not turn on at a voltage and turn off at 0V.

This should be a comment to @Majenko 's answer, but since I'm newb on this side, it goes as answer: Isn't the speed of the fan more dependent on the AC frequency than on the effective voltage? Would this really work, and in what range of speeds?

The multispeed AC motors used in ceiling fans do not use resistors to change the speed, they use different taps on the motor as an autotransformer to scale the voltage used in the motor.   http://electronics.stackexchange.com/questions/86459/whats-the-theory-behind-speed-control-of-a-multi-tap-multi-pole-induction-motor

If torque-dependent slip is built into the motor, as is true in the multi-speed fan motors, then the amount of slip and speed, relative to the no-load synchonous speed, is dependent on the load and voltage applied.    Reducing the energy input by chopping out part of the waveform also increases the slip.

@Gleb I did convert it but create a few nice answers and you'll get yourself commenting privileges.

I've read this answer multiple times over the last week, and it's still confusing. Is this for single-speed or multi-speed fans? Is there even a difference? Could you provide code samples for Arduino that would assist in understanding the cut-offs on the sine wave? Is this how wall fan-dimmer switches work?


text:
Arduino stk500_getsync(): not in sync
We have an arduino pro mini, we are trying to trying to upload sketch the controller but we are prohibited, as the arduino attempt to upload the sketch, it display an error of: not in sync.
We are pretty new in this are, so any help would be much appreciated.
Our setup is: -Breadboard -Connection to adapter: USB Serial. -Arduino Pro Mini as a controller
Through the Arduino Programming Client.
The processor and the port are setup op properly.
The strange thing is, it has worked sometimes these past days..
Much Thanks.
Mieer

Try pressing the reset button just before uploading, might be that the reset signal isn't sent right as it's going through the adapter.

If your error is intermittent, check all of your wiring to ensure there is nothing loose, and try hitting the 'reset' button the Arduino as the compile message changes to uploading, in case your serial adapter isn't resetting the Arduino properly.


text:
Hc Sr 04 Ultrasonic Sensor
I'm using Hc-Sr 04 ultrasonic sensor for my project and I want to know that if I could or not utilize an slope. Have you an idea?

Do you mean "chirping"? No, the device outputs a fixed 40KHz frequency (8 cycles worth per ping).

No, i mean can i use in a slope place this sensor? i m getting right values when i used in straight place.

I'm sorry, I don't know what you mean by "use in a slope place"

Do you mean detecting the distance to a non-perpendicular surface?

Partially yes, we can say @PeterR.Bloomfield. i want to use 30 degree angle tilt HC SR 04. is this possible?

Still don't understand quite what you are asking.  They say a picture is worth a thousand words.  Can you draw one for us depicting what you mean?

Can't you just try? You seem to have a working setup for perpendicular surfaces ("i m getting right values when i used in straight place."), so check how the values change when you rotate the surface (or move the HC accordingly).

A perfect surface at an angle to the perpendicular would give no reflection back to the module (it goes off at another angle, just like a mirror or a ball kicked against a wall), but most surfaces aren't perfect.  In practice you will likely get some reflection but at greatly reduced range.  If your sloped surface is smaller than the beam width you may also get a reflection off of its perimeter.

I'd suggest running a google search using "hc-sr04 reflection angle" there are a number of existing thoughts and posts on this idea.  One of the most interesting items are the diagrams that show reflected signal drop-off as a function of angle of incidence to object.  The bottom line is that this is not an accurate measurement tool for non-perpendicular objects.  Adding multiple receivers ... for example at -45o, 0o and +45o  may give you better data.

I have a couple of these running right now, and they will often work at a slope when the surface is complex (not flat). However, the detection angle, as it comes from the sensors, appears to be about 30deg from centre in each direction. Hence, the sensors do need to be relatively pointed at the object being detected.
When placing my hand directly above it, it doesn't really matter what angle I tilt my hand, presumably since I have fingers that are not flat. On the other hand, if I put a paper towel in front of it, it will stop seeing it if I angle the paper towel more than 20 or so degrees.
Overall, if you keep the object within 30 degrees from the sensor's fixation point, it will work, granted the object, if flat, is "pointed" at (facing) the sensor flat-wise within about 20 to 25 degrees. For irregularly surfaced objects, it does not seem to matter too much unless the angle is pretty steep, such as 60 degrees.
Here is what I mean:

Slope surfaces may cause reflections so you need to try. I think 30 degree going to make reflection and gives wrong value


text:
I guess, pull-up/down resistors fried. What can i do?
Arduino Mega ADK is working well but it is not working circuit in which pull-up/down resistors. It is generating wrong results. I guess, pull-up/down resistors fried. What can i do?

Replace them...?

@Majenko i didnt get

You and me both. I don't have a clue what you're asking. Your question needs to be about 100 times the length it is. Just asking "I don't think X works, what do I do" will not get you an answer - least ways not one you can make any sense of.  You need to describe what you have done, describe the results you expect, and most importantly describe the results you are actually getting. Schematics, pictures, code - all of it.

This site is not like your typical forum structure where you discuss the problem in a thread. You get one place to ask your question, and that question is all you get. It has to contain everything we need to be able to work out what is wrong.

@Majenko i know this site's principle. i want to say that i dont understand your comment and typed "didnt get it". you didn't need to wax eloquent.

Well, I see no attempt by you to ask a reasonably understandable question, so I figured you needed some help to understand what you needed to do in order to get the help with your project you require.

If you want internal pullup or pulldown resistors on input pins, you can use external ones to do the same job as internal ones if you wish to. Generally, if you use say 100 k Ohms from a pin to V+ or ground then it will act as a pullup or pull down respectively on an input pin, but have much effect on an output pin - which is what you want to happen.
However, it is unlikely that 'fried internal resistors is the reason for code not working and, if this is the case, there is probably unknown and unknowable other damage as well. Pull up/down resistors are usually not actually resistors. They are FETs with high Rds_on values that look resistor like when on. Anything that "fries" them has a reasonable prospect of doing other damage as well.


text:
Arduino due - SAM-BA bootloader is it there even if you replace the original chip
On this page http://playground.arduino.cc/Bootloader/DueBootloaderExplained it mentions the sam-ba bootloader is permanently burned into the rom of the chip.
Does this mean even if I buy a new chip from Farnell, it will still have the bootloader in or is just ones that are specifically made for the arduino due?
That is different from say the mega328, with the mega328 I have to burn the bootloader on manually using isp programmer/ buy it preprogrammed.

Yes, for the Due, but No, for a Zero or Adafruit Feather M0.
The Due uses the Atmel SAM3X8E featuring:

16 Kbytes ROM with embedded bootloader routines

As a ROM the contents are fixed during manufacture, so would be there in a new chip.
However it is worth noting that many SAM devices including this one have the NVM bits that are much like the fuse bits on an ATmega.  Here GPNVM bit 1 defaults to 0, enabling the bootloader, but if set to 1 the bootloader will be skipped.   Hence it may well be possible to get one into a state where the bootloader is not available.  They also have an "erase" pin which if driven high during startup will restore the default state (bootloader invoked) of this NVM bit (and erase whatever you put in flash).

In contrast, the Arduino Zero and the Adafruit Feather M0 also use Atmel "SAM" chips with "SAM-BA", however, they use the SAMD21, where the situation is a bit different:

Unlike
  existing SAM products, ROM monitor is not available in SAM D21 and SAM-BA will
  be loaded in Flash memory.
SAM-BA bootloader is not factory programmed on SAM D21 devices and has to be programmed using an
  external programmer.

Incidentally, congratulations on being willing to step beyond the ATmega DIP packages - more people need to learn that surface mounts part (or at least the TSSOP and LQFP varieties) are something that can be worked with by hand.  If you do not have hot air tools, make sure to only solder one corner, check alignment, solder the opposite and recheck, etc.  But hot air will save you so many headaches and a solder station with it is now in the $60-70 range.
Finally, while you do have the bootloader available in the SAM, to really take advantage of all of its capabilities you will want to get an SWD interface - in addition to programming without reliance on the bootloader, this exposes things like breakpoint debugging, which while almost never "necessary" can still be quite convenient and useful.   Atmel used to offer a great deal on the PCB of the SAM-ICE pod less cables kit and housing, unfortunately there was a massive price increase after the Microchip acquisition.
SWD programming is effectively vendor-unique software operations performed on top of a standard signalling scheme, so you do have options for programmers from other sources - you can make a functional if quite slow CMSIS-DAP from an MBED board (or apparently an Arduino Pro Micro) that will work for debugging but be slow at flashing, you can probably use a Raspberry pi, or the more advanced FTDI devices with the MPSSE engine such as FT232H/FT2232H/FT4232H (but not the everyday FT232RL).  With alternate programmers you will probably need to use something like openocd for the host software - Atmel Studio likely only supports their own and perhaps a few pricey alternatives.

Just out of curiosity what programmer would I need to program this chip if I wanted to use an external programmer. Say I wanted to change some fuses and update the firmware for example.


text:
Arduino Mega: which Digital pins are already used for something?
I got an Ethermega, and learned that Pin 13 already has a LED.
Are there other digital pins with special circuitry or already allocated to a specific function? (like usb,serial,ethernet,sd, etc)
I need about 30 inputs so I can skip some if that would avoid headaches.

Have you checked the schematic and datasheet yet?

http://arduino.cc/en/Main/arduinoBoardMega , also you could try some external IO inputs with http://tronixstuff.com/2011/08/26/tutorial-maximising-your-arduinos-io-ports/

D4: ChipSelect for the SD card reader (can be used if no SD is present)
D0 and D1 are Serial RX and TX (just like any other arduino)
D10: Ethernet enable line
D13: led. Led is connected via a mosfet, so it doesn't interfer (like on the uno)
D50, D51, D52: SPI for the ethernet chip and SD card
All this was found in the schematic

Don't worry about the led on pin 13, it just sits there but doesn't block anything.
You can still use the pin as a normal IO pin.
You didn't mention whether your 30 inputs are digital or analog, so let's have a look at digital input first.
I have never used the MCP23017 mentioned by Martynas, but the linked article looks very interesting and I'll definitely order one of these amazing chips!
Another option might be using 8 bit PISO (parallel in - serial out shift registers, such as the 74HC165. Consider this as the complement to the 75HC595 for output. These shift registers are dirt cheap (around 0.3 €), are available as DIP (important for breadboarding) and can be run via SPI.
Advantages:

it's fast to read in 8 digital lines into a byte (why would one want to use more than a bit for the state of a digital input?)
the shift registers can be daisychained, subsequent calls of ShiftIn allows to read all (digital) input states into a corresponding data structure (array of bytes, etc.) using just three pins on your Arduino.

Klaus i wanted to mention 74HC165 :) but MCP23017 link was open already so i just copied it to give the main idea:) +1

@Martynas I think it was a splendid idea to mention the MCP23017! As written by John Boxall in the article that you linked: "...I think the I2C bus is underappreciated".


text:
ATTiny84 blink mystery
Novice mode, please.
I programmed my ATTiny84 using Arduino Ethernet (Arduino IDE 1.6.7) using https://github.com/damellis/attiny branch - 1 MHz internal oscillator mode. I uploaded ISP sketch to Arduino with all cables disconnected (first I did it with all of them connected but Arduino didn't seem to mind), connected the whole setup using 10 uF capacitor and the sketch got sent into ATTiny84 without problems.
Blink sketch is using atttiny84's digital pin 7 (that is physical leg No. 6) set to 1 s blink rate.
But, when I connect an yellow LED, it won't blink. I'm not yet good enough with my oscilloscope (don't know how to hook it up) but my multimeter is showing something weird - voltage is slowly rising on DP7 (I measured against ground) - over approx. 5-6 seconds to 400 mV, then immediately jumps to 1V (not sure about this, could be measurement bug) and then right to 0V.
Blink sketch:
int led = 7;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

I'm clueless. Please confer.
Thank you.
Images of my setup:

From the picture it appears the LED is connected with its cathode to VCC. It won't conduct in that way...

Test the LED without using the pin. That is, move the wire from the LED straight to Gnd or Vcc. Make sure the LED turns on and off. Then put a multimeter on the pin.  Make sure that turns on and off.

Nick, I have connected the diode directly to chip's VCC to test out whether LED's circuit is ok. It glows immediately. When I connect it back to DP7, it does nothing, but there are these rises to 400 mV on that pin against ground.

I solved my own problem. Wiring was completely OK, so was flashing.
The problem was RESET pin (4th physical pin). As soon as I disconnected it after flashing, LED started blinking. If someone knows why, I'd appreciate some info.

Did you measure the RESET signal before you removed it? Was it low, high or floating? This could help answer your question. My guess is that it was low and therefore the ATtiny did not start.

Just tried to measure it with my oscilloscope. It's 13.44 mV Mikael, so I guess that can be considered low? Can you briefly describe why this prevented the chip from starting it's program? Thank you.

The MCU is reset by a low pulse on RESET. Holding it low will generate an internal reset but the MCU is not started until RESET goes high again. Please see http://www.atmel.com/images/doc8006.pdf, chap. 8.2.2, pp. 41.

Thanks Mikael. Good information, surely will help many people.


text:
Dragino lg01-p problem with serial monitor
i have a dragino lg01-p lora gateway to which i successfully communivate through lora with an arduino and i can program it through network as expected and seen in its manual with the demo client-server code. However, when i try to open the serial monitor on the side of the dragino, i get this:
Unable to connect: retrying (1)...
Unable to connect: retrying (2)...
Unable to connect: retrying (3)...
Unable to connect: retrying (4)...
Unable to connect: is the sketch using the bridge?
I need to have the serial communication cause i made a little app in C# which gets the data from a COM port. I also tried with Console instead of serial, but still didn't get any results back. This is the code, exactly as is in the examples no the manual
#include <SPI.h>
#include <RH_RF95.h>

// Singleton instance of the radio driver
RH_RF95 rf95;

int led = A2;
float frequency = 868.0;

void setup()
{
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  Serial.println("Start Sketch");
  if (!rf95.init())
    Serial.println("init failed");
  // Setup ISM frequency
  rf95.setFrequency(frequency);
  // Setup Power,dBm
  rf95.setTxPower(13);
  // Defaults BW Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
  Serial.print("Listening on frequency: ");
  Serial.println(frequency);
}

void loop()
{
  if (rf95.available())
  {
    // Should be a message for us now
    uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
    uint8_t len = sizeof(buf);
    if (rf95.recv(buf, &len))
    {
      digitalWrite(led, HIGH);
      RH_RF95::printBuffer("request: ", buf, len);
      Serial.print("got request: ");
      Serial.println((char*)buf);
      Serial.print("RSSI: ");
      Serial.println(rf95.lastRssi(), DEC);

      // Send a reply
      uint8_t data[] = "And hello back to you";
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent a reply");
      digitalWrite(led, LOW);
    }
    else
    {
      Serial.println("recv failed");
    }
  }
}

Found it so i will share my problem here to help someone else!
Apparently Bridge funcions work better for this device if you include Process.h rather than Bridge.h.

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


text:
Is this set up appropriate?
Hello Internet Arduino enthusiasts!
I'm totally new to Arduino and as my first project, I'd like to make a controller connected to computer A (the master) and computers B and C as 'slaves'.
The master would simply send commands as USB mouse and USB keyboard inputs to slave computers through an Arduino controller. Think of it as a hardware KVM switch (without the V(ideo)).
Now, I'm planning to work on that during the Christmas vacations, so I need to order the parts now to receive them in time.
I was thinking I could use these parts:

Arduino Due (because it has the capability to send keyboard and mouse input)
2 SparkFun FTDI Basic Breakout - 5V, one for the mouse, one for the keyboard (per target computer) (https://www.sparkfun.com/products/9716) (because I can convert it to a 3.3v, what the Due is using)

Please consider:

The price is not really an issue for now.
I'm not worried to much about the programming.
I'll figure out how to make it work once I have the time and the items.
I know someone who has a starter kit from SparkFun, and there is an electronic store closeby, so I'm not worried about the wires.

Will I be able to make what I'd like with those basic parts, or am I missing something?
Thanks!

You need:

two MCUs that can act as USB devices (one per slave),
some way of getting the commands from the master to the MCUs

That means two Arduino Dues (or Arduino Leonardos, or SparkFun ATmega32U4 breakout boards, etc.) and one USB device of some sort that you can talk to and have send commands to the MCUs.
And perhaps something to transport the commands from the master to the slaves, but you need to think about the programming for that first since the transport and the programming will be very closely connected.

Ok, so if that someone I mentioned earlier has an Arduino Uno, I would need two Due/Leonardo, and a bunch of wires and something like this (http://arduino.cc/en/Tutorial/MasterWriter) to make them communicate together? Computer A would tell Uno to tell Dues/Leonardos to tell computer B and C how to move the mouse/keyboard, right? Thanks for your input!

I2C is not the right protocol to use for this. Normally it would be done via UART, with conversion to RS-485, ZigBee, etc. if called for.


text:
Time based scheduling, NTP vs delay()
Without asking an open-ended question, i wish to find the best way (resourcefulness) to execute methods from an arduino based on time.
in a nutshell, every 10 minutes i want functionA() to be called & every 30 minutes, functionB(). At this point i'm unable to specifiy whether a method would need to be called at a less frequent rate, however i wish to assume that one may.
My 2 ideas so far:

encapsulate the functions a & b inside the NTP client, and execute based on the minutes in an hour

or

use delay() or even the milli() counter with functions a & b below inside the loop.

My main worry of the 2nd option is that the arduino handles time keeping itself, in a long run (lets say 1 year), the arduino will end up with no memory left. Whats is the consensus with this?
Board wise, to be run on Uno & Mega.

You may want to separate the task of keeping time from the task of running some function at even intervals in your mind, they are different problems.

Connect a battery backed up Real-Time clock to your arduino and use that to keep track of the time.
Basically the same idea as NTP but minimal hardware is required and you can get an RTC with the long term accuracy you need.

memory used by delay() and milli() (if any) will be recycled every time you call it, so it does not add up. You should be aware that milli rolls over (resets back to 0) after approximately 50 days - see http://arduino.cc/en/Reference/Millis - you will need to keep track of how many times it has overflowed, and include that in your calculations.
delay will only be useful if you do NOTHING AT ALL during that time - if you want to do other stuff in that space, you should use milli(). Also, if you delay (without using milli()), your events will drift by the time it takes to run the code. delay() and milli() will also only be as accurate as the crystal on your arduino - it should be no more than 20 parts per million; this comes to 10 minutes per year. This may or may not be a problem.
NTP will use a lot more resources, and has to be polled. It is also potentially less reliable (i.e. NTP may be down for short periods).
If you need accurate timing, the best solution would be to use delay() to pass the time (approximately), milli() to keep the time, and adjust for drift with NTP.

Both NTP and milli() waste a lot of processing as it keeps the Arduino busy checking if the time is right.
Your best bet is to use the Arduino timer. Set the timer to interrupt every 10 minutes. If you don't need to do anything aside from functions A and B, you can let your Arduino sleep and keep power draw to a minimum.
// Example code
void funcA(){
    // do stuff
}
void funcB(){
    // do stuff
}

void setup() {

    // initialize Timer1
    cli();          // disable global interrupts
    TCCR1A = 0;     // clear TCCR1A
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
    // 15624*1024/16000000 = 1sec at 16MHz
    OCR1A = 15624;
    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);
    // use 1/1024 the speed of the clock:
    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);
    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);
    // enable global interrupts:
    sei();
}

ISR(TIM1_COMPA_vect)
// Your task manager here
// This function decides when to execute the functions A and B
{
    static t1= 0;
    static t2= 0;

    // increment your counter flags
    t1++;
    t2++;

    if (t1==10) {//runs function every 10 sec
        funcA();
        t1=0;
    }
    if (t2==30) {//runs function every 30 sec
        funcB();
        t2=0;
    }
}

void loop(){

    // do stuff or sleep for even more power saving
}

Hope this helps.


text:
SIM900A GSM/GPRS Shield Transaction per minute
I'm planning to buy SIM900A GSM/GPRS Shield for Arduino Uno. I wanted to create an application that sends SMS to a list of mobile numbers, let's say 1000 mobile numbers. Is it applicable to use SIM900A GSM/GPRS shield for bulk messaging? Did anyone of you tested the sms transaction sent per second/minute using this shield? I accept any suggestion that would be helpful. Thanks.

Sound like you need an online sms gateway (.e.g. message bird) .

Yep, but this is only for my testing purposes for a few mobile numbers. Thanks

"Did anyone of you tested the sms transaction sent per second/minute using this shield?" This depends on the service provider, the radio network, more than the SIM900A.


text:
Ethernet shield not getting IP
I am just running the below DHCPAddressPrinter sketch in Arduino example to setup EthernetShield with MAC and IP
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  // start the Ethernet connection:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // no point in carrying on, so do nothing forevermore:
    for (;;)
      ;
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
}

void loop() {

 }

After uploading the sketch to arduino,below is the output shown in console
Sketch uses 13,614 bytes (42%) of program storage space. Maximum is 32,256 bytes.
Global variables use 539 bytes (26%) of dynamic memory, leaving 1,509 bytes for local variables. Maximum is 2,048 bytes.

And there is nothing shown in Serial monitor
This is the image of Ethernetshield's some leds glowing after connecting to Router.
My router is Binatone Wireless ADSL2+ Router.

I checked arp -a,
C:\Users\Radhamani>arp -a

Interface: 192.168.1.6 --- 0x3
  Internet Address      Physical Address      Type
  192.168.1.1           6c-fd-b9-24-c6-fe     dynamic
  192.168.1.255         ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static
  255.255.255.255       ff-ff-ff-ff-ff-ff     static

Interface: 192.168.198.1 --- 0xe
  Internet Address      Physical Address      Type
  192.168.198.255       ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static

Interface: 192.168.234.1 --- 0xf
  Internet Address      Physical Address      Type
  192.168.234.255       ff-ff-ff-ff-ff-ff     static
  224.0.0.22            01-00-5e-00-00-16     static
  224.0.0.251           01-00-5e-00-00-fb     static
  224.0.0.252           01-00-5e-00-00-fc     static
  239.255.255.250       01-00-5e-7f-ff-fa     static

Complete result of ipconfig:
Wireless LAN adapter Wi-Fi:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::901:3297:48ad:9e7d%3
   IPv4 Address. . . . . . . . . . . : 192.168.1.6
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.168.1.1
Ethernet adapter VMware Network Adapter VMnet1:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::c954:40b2:c8c1:de0%14
   IPv4 Address. . . . . . . . . . . : 192.168.198.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :
Ethernet adapter VMware Network Adapter VMnet8:
   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::2837:7e01:c799:d627%15
   IPv4 Address. . . . . . . . . . . : 192.168.234.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

Serial.println in the program is not printing anything.Looks like Ethernet shield is not getting IP.I am not sure where I am wrong.Please help me to fix this issue

Based on the image .. i see that the programmer pins at the back of the shield and the arduino aren't connected properly.. That might be the error or at least happened with me.
Apart from that, certain network need to identify the mac address from a look up table and if the shield mac address matches, then only network transactions are allowed.
Also i suggest you to drop the virtual machine mac address and networking protocols and try upon the base OS which you have on your computer.

I had the same problem and it had two causes:
1) I couldn't fully insert pins of my shield into the board (ArduinoMega), because if its USB connector. So I connected them with cables. To check for this error, use this code to initialize your Ethernet shield:
   Ethernet.begin(mac, ip);
   if (Ethernet.begin(mac) == 0) {
     Serial.println("Failed to configure Ethernet using DHCP");
     Ethernet.begin(mac, ip);

     if (Ethernet.hardwareStatus() == EthernetNoHardware) {
       Serial.println("Ethernet shield was not found.");
     } else if (Ethernet.linkStatus() == LinkOFF) {
       Serial.println("Ethernet cable is not connected.");
     }
   }

If this is the case, it will print "Ethernet shield was not found."
2) I'm using this Chinese W510 shield too (the same as on the photo above). Apparently, there's a known bug. Here is the solution: https://forum.arduino.cc/index.php?topic=351477.45
In short: You have to solder 2 resistors between pins 1-2 and 3-6 of the shield's Ethernet connector. No need to unsolder anything.
Works great!

The SD might need disconnecting. Add below to setup().
pinMode(10, OUTPUT);
digitalWrite(10, HIGH);

Also check the pin assignment for the W5100 (in the Ethernet library).
Cheers!

check the DHCP service of your router is active or not :)

I had the same problem with my project in which I was using Arduino Ethernet schield 2. I suppose to get the IP address in serial moniter using simple sample program but later I found that when we use Arduino Ethernet schield 2 we need to use the library "<Ethernet2.h" instaed of Ethernet.h


text:
Using Arduino IDE as an API
I have a project where it would make a lot of sense to generate Arduino compatible source code, compile it and flash it based on some settings in the project software.
Is there any way to do this without having to rely on the user having installed the Arduino IDE/java?
The ideal would be a self-contained library that could be linked to my C/C++ program.

For compiling and uploading Arduino code, you do not need Java, nor the
Arduino IDE: you need avr-gcc, avr-libc, the Arduino core library and
avrdude. With a proper Makefile, your program just needs to
system("make upload");

C.f. the tutorial Compiling Arduino sketches using
Makefile.
On an Ubuntu or other Debian-like OS, you would just
sudo apt-get install arduino-mk make to get everything you need installed.

Have you tried Arduino C Scaffold project?

...the scaffolding lives on Github in the Throw The Switch organization as the Arduino C Scaffold project. This should have everything you need to deploy a C project on an Arduino UNO without the Arduino IDE. If you know your way around Git, you can clone this repository and get to work. If you’d rather not mess with Git right now, you can download the latest revision of the scaffold in a zip file. Once you have the scaffold, take a look at the README. This will walk you through getting the AVR toolchain setup on your environment and describe some of the different ways to use the scaffold.
  -- https://spin.atomicobject.com/2011/10/15/taking-the-training-wheels-off-the-arduino/

Will check it out!

This seems to be targeted at plain C, not Arduino code.


text:
Cannot receive data from GPS SD Shield V2-B
I am attempting to receive GPS data from a GPS SD Shield V2-B purchased from maplin. I have attempted the very simple sketch they provide on their website linksprite.com.
I have also tried following a tutorial found here: http://tronixstuff.com/2014/01/15/tutorial-arduino-mediatek-3329-gps/.
This is the code i am using:
    // Example 19.1

    #include <SoftwareSerial.h>
    SoftwareSerial GPS(2,3); // configure software serial port -

    void setup()
    {
      GPS.begin(9600);
      Serial.begin(9600);
      pinMode(13,OUTPUT);
    }
    void loop()
    {
      byte a;
        if (GPS.available() > 0 )
      {
        a = GPS.read(); // get the byte of data from the GPS
        Serial.write(a);
        digitalWrite(13,HIGH);
        delay(1000);
        digitalWrite(13,LOW);
        delay(1000);
      }
    }

I am using an Arduino 101. The jumpers on the GPS shield are set up as follows:
I have attempted using both power simply from my Mac and an external 9V battery connected to the Arduino.
The 'blink' has been added the sketch to test whether data was being received but there was a problem with the serial monitor. This is not the case because the blink did not occur. It however did occur when moved outside of the if statement as you would expect.
Any help or suggestions would be much appreciated.

Sounds like hardware, if you are using an existing sketch and shield. Did you solder the pins onto the shield, or just push them in?

The shield came pre-assembled so didn't require any soldering. The jumpers used are removable and are just pushed on

You need to set the jumps as per the instructions that came with the shield ...
PAGE4 : short jumpers TX and MRX .... and RX and MTX


text:
Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?
Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?
This is the Chip I have. On the chip it says ProMini R160JAC6v. and When i program it. It programs under 5V 16MHz with ATmega 328

Here is the bluetooth chip I am powering:

VCC is likely an input.  What is on the other end of the yellow wire that goes off the pic?

If you power from USB the vcc pin gives you the voltage that USB is providing. Somewhere between 4.75 and 5.25v.
If you use external power it provides 5v since that is what the regulator provides.
The current limit is either the limit of the usb port or the limit of the regulator on your board. Check the datasheet for that regulator (hint: read the schematic to find the model of the regulator).

Where can I find the USB 5v pon? I've been having a hard time finding the data sheet for that particular board. Maybe I'm looking in the wrong places? I've just tried typing in the specs of the board in google but havn't gotten the specs for that board.

If it is a genuine arduino the schematic will be on the arduino website. If it is a cheap chinese copy, you are on your own. It looks like an LM1117-5, and as such will most likely be 800mA. Pon = pin translated through my tablet's onscreen keyboard. Edited it.

And then there are these concerns:  https://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/


text:
Use only one pin as serial output/input with arduino
I'm looking for a way to use Arduino UNO's as serial outputs or input "individually", I don want to have an RX pin for each TX pin. I know the library SoftwareSerial, but I'm not sure if it is posible to achieve my objective with it.
I have also read that in this library "If using multiple software serial ports, only one can receive data at a time". Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?
Thank you for your time.

The reason you can't receive more than once channel at a time with software serial is that there is only one CPU - how can it process two asynchronous channels at the same time?

@TomCarpenter It's certainly possible but it would require some gnarly interrupt-driven sampling/sending, and would work only at limited (relatively low) baud rates.

@SpehroPefhany I was talking about the SoftwareSerial library which uses busy loops for generating the baud rate. I should have made that more specific. Yes you can potentially do it if you write your own RX code of find one which doesn't block.

@RobhercKV5ROB This one is probably best migrated.

what are you communicating with? could you possibly use another protocol, like I2C/TWI?

I don't want to have an RX pin for each TX pin ...

I adapted the SoftwareSerial library a while ago to omit the receiving part. You can download that from:
http://www.gammon.com.au/Arduino/SendOnlySoftwareSerial.zip
You use that like SoftwareSerial but if you read you will always get -1 returned, and available always returns 0.
The constructor only has the transmit pin:
  SendOnlySoftwareSerial(uint8_t transmitPin, bool inverse_logic = false);

Is there any library or method I can use to achieve both of my objectives, using pins "individually" and receiving data from more than a pin at a time?

You don't want an Rx pin, but you want to receive from more than one pin at a time? Now you've lost me.
Sounds like an X-Y Problem - maybe describe this requirement in more detail.
Having said that, hardware serial can receive from one pin while the processor is doing something else. If you have a Mega you could receive from 4 ports at once (it has 4 x hardware serial ports).

AVR304, "Half Duplex Interrupt Driven Software UART on tinyAVR and megaAVR devices" describes how to implement a half-duplex software UART using 2 pins. Simply omit the half of the UART that you do not need in your own implementation.

Serial ports do not require both directions to work. You can connect just one if you want. Of course you won't be able to reply or receive but you know that. Multiple TX from a microcontroller is easy. Just send the data at the speed required. RX is harder because you have to be able to read multiple high speed random inputs at the same time. It requires careful and complicated coding and will not be small or simple. You may not be able to do it and the rest of your project as well.
There are ICs or setups that can multiplex serial lines though. See https://electronics.stackexchange.com/questions/111491/multiplexing-ttl-serial-lines-with-transistors


text:
ICT Bill Accepter
I have a ICT a6-15scp-usd4-ii. I have all of the wires for it. I dont have the gambling machine it came out of and it was laying around. Is it possible to make a Light come on when a bill is put in? Can it be wired to the arduino to act as a switch per-say? If more info is needed let me know. I will make a tutorial for this if it works.

Bill acceptors are notoriously hard to work with because usually the datasheet and or manual are usually only available under NDA. You will probably just have to reverse engineer it.

ill give it a shot, but it is not looking good.

Looking at the only doc I can find, http://www.ict-america.com/docs/a6v6/A6.V6-MXP4.pdf it looks like if you have the A6 version there is an RS232 port somewhere, which means the most you would have to do is level translation. If you have the V6 it will be using MDB, which is typically a 9-bit UART. There is an implementation of MDB found here: https://github.com/MarginallyClever/MDB-Sniffer

What kind of interface does your model have? Because when you have RS232 it should be fairly simple to see what it'll print out when you enter bills into it.

frst you're going to have to send an command to the bill acceptor to tell it to accept bills, they you just need to find the wire that pulses when a bill is inserted.

Go to ICT's website to download the Installation manual (one used for many different models), there is info on the pinout for every pin on your model, along with recommended I/O interface circuit.
I am using a different model, but from what I know, if your model is a "Pulse" model, which means that when a bill is accepted, there are pulses that you can captured (the pulse width is pre-set by toggle switches, and the number of pulses depends on the value of the bill).
What I would do is to use interrupt to listen to these pulses. When the interrupt triggers, light up your LED.

ICT a6-15scp-usd4-ii is a pulse/parallel bill acceptor. Here is the datasheet, the link in the comments is broken. A6 version uses pulse/parallel protocol (V6 version is MDB). The 110V version that you use has only pulse protocol.
Take care with the wiring, the acceptor uses dangerous  110VAC voltage.
I understand you want to make same kind of pay per time device like those used in kiddie rides machines.
There are many examples on the internet on connecting a pulse bill acceptor to Arduino. The theory is simple the bill acceptor has a PULSE output, usually in negative logic, high in idle, that send a low pulse for each monetary unit, 1 for 1$, 5 for 5$ and so on.
Sometimes, like in your case, the bill acceptor has an enable input through which you can enable or disable the acceptance. But in A6 110V this input must be connected to hot 110v lines so it's harder to handle through Arduino so you will need to use a relay or to leave-it active all the time by setting dip SW 8 to ON, see page 6 and page 9 in the manual.
The electrical connections.
See the connector pinout , page 5
The credit (pulse) output uses an optocoupler so it has two lines CREDIT_RELAY_COM (pin 1) on the above connector that must be connected to Arduino GND and CREDIT_RELAY(N.O.) (pin 16) that must be connected to the digital input of Arduino that read the pulses, this digital input must have a pull-up resistor to 5V, it might be the built in pull-up activated by using pinMode(PIN, INPUT_PULLUP) but better an external resistor 1k to 4.5k.
And, of course, the main power supply , pin 4 and pin 20 to main 110 voltage and don't forget the earth ground, pin 21 for safety.
Bill acceptor dip switch settings
See the page 6 of the manual. For the moment just put SW8 to ON (acceptor enabled) and all other to OFF (all bills enabled, one pulse one dollar, 50ms/50ms pulses)
The Arduino source code
To count the pulses from a pulse bill acceptor or coin acceptor there are many examples on the internet but I did one myself, very easy to use, find the source code here, that counts the pulses in background using timer1 interrupt. In this way the main loop is free for other tasks you need. You can strip the LCD part of the code if you don't use.
To work with ICT A6 you need to modify the some defines in the code: PULSE_WIDTH to 50 form 100 and PULSE_DELTA to at least 4 from 2 (because it's to small).
Connect Arduino A0 input to pin 16 (CREDIT RELAY) and to a pull-up resistor to 5V as I pointed above, and Arduino GND to pin 1 (CREDIT_RELAY_COM) and power the Arduino from some different source or through USB and the example should work now. Obviously the BILL_ACCEPTOR_ENABLE and BILL_ACCEPTOR_DISABLE macros will not work the acceptor is always enabled.
To actually make-it work as pay-per-time machine a suggestion of code will look like this:
unsigned long finish_time = 0;
#define MS_PER_DOLLAR 600000 //10 minutes
//add to setup
turn_off_the_light();// Switch a pin or something

void loop(){
  unsigned long temp_millis;
  unsigned long temp_credits;
  temp_millis = millis()
  temp_credits = read_and_clear_pulses();
  if (finish_time < temp_millis) finish_time = temp_millis;
  finish_time += tempcredits * MS_PER_DOLLAR;
  if (finish_time > temp_millis)
     turn_on_the_light();
  else
     turn_off_the_light();
// Do something else
}

If you use the device uninterrupted for more than 49 days you will have the millis rollover issue  but you can find examples on the internet how to handle this.

So I know this is an old post, but I have interfaced with a BV20, and noticed most of the ICT validator's have a "busy" line that is asserted whenever the unit is transporting, validating, or storing/stacking a bill.  If you want to light something up when a bill is being handled, but not necessarily validated, that might be what you are looking for.


text:
Simple webpage serve with Arduino ethernet shield on SD card
I have been experiment with the arduino uno board from few days but can't seem to make it serve web page stored in SD card of ethernet shield.
If I print the contents of the file to serial it works properly, even embedding the HTML code works fine, but client.write() just produces a never ending garbage text of ÿÿÿÿÿÿÿÿÿÿÿÿ
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 0, 115);
EthernetServer server(80);

File webFile;

void setup()
{
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);
    Ethernet.begin(mac, ip);
    server.begin();
    Serial.begin(9600);

// initialize SD card
Serial.println("Initializing SD card...");
if (!SD.begin(4)) {
    Serial.println("ERROR - SD card initialization failed!");
    return;
}

Serial.println("SUCCESS - SD card initialized.");
// check for index.htm file
if (!SD.exists("index.htm")) {
    Serial.println("ERROR - Can't find index.htm file!");
    return;  // can't find index file
}
Serial.println("SUCCESS - Found index.htm file.");
}

void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
        if (client.available()) {   // client data available to read
            char c = client.read(); // read 1 byte (character) from client
            // last line of client request is blank and ends with \n
            // respond to client only after last line received
            if (c == '\n' && currentLineIsBlank) {
                // send a standard http response header
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println("Connection: close");
                Serial.println("starting to open htm");
                client.println();
                // send web page
                webFile = SD.open("index.htm");        // open web page file
                if (webFile) {
                    while(webFile.available()) {
                        client.write(webFile.read()); // send web page to client
                    }
                    webFile.close();
                }
                break;
            }
            // every line of text received from the client ends with \r\n
            if (c == '\n') {
                // last character on line of received text
                // starting new line with next character read
                currentLineIsBlank = true;
            }
            else if (c != '\r') {
                // a text character was received from client
                currentLineIsBlank = false;
            }
        } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
} // end if (client)
}

Sorry for the poor formatting, I just copied it from tutorial, please help me out.

Where are you viewing the results of client.write()? From a web browser? Have you tried opening the file before you start writing to the client, maybe in setup()? In case opening the file takes too long and is causing the process to time out? Show us the contents of "index.htm".

Me I solve the problem by using : "/index~1.htm"
I see that the file name is seen like that using the cardinfo.ino from Example

because you copied a file with 4 characters length "html" extension to file system with max 3 chars extension

"ÿ" is character code 255, the erased state of a Flash/EPROM/SD. Check if your SD card format OK, 'index.htm' file is there, and your code can read it.

SD card is formated in FAT16, and I've been able to get the data of files on serial output | replacing client.write() to Serial.write() ; i.e. it seems file is accessible