Trouble with loop (arduino) - c

I am trying to create a small stall at school using and arduino,
the project is to scan items using a barcode scanner enter the price and issue a receipt. the barcode scanner is connected to serial port and keypad and printer are connected via software serial. I am using a 3.5" tv as the display. the items can be identified by the first 3 digits of the barcode. I want to include the item names somewhere in the sketch and match and print them when the string starts with their number.
I have created a sketch with a lot of help from other forum users but the date is being repeatedly printed and not much else is happening. How do I make the date print only once. and also how do I buffer data from serial and software serial before printing.
//#include <TVout.h>
//#include <video_gen.h>
//ARDUINO 1.0 COMPATIBLE ONLY!
//ARDUINO 1.0 COMPATIBLE ONLY!
#include <Time.h>
#include <DS1307RTC.h>
#include <SoftwareSerial.h>
//#include <LiquidCrystal.h>
#include <Thermal.h>
#include <Wire.h>
//TVout TV;
int printer_RX_Pin = 3;
int printer_TX_Pin = 4;
int incomingByte = 0;
Thermal printer(printer_RX_Pin, printer_TX_Pin, 19200);
String readString; // a string to hold incoming data
//SoftwareSerial mySerial(10, 11);
void setup(){
//TV.begin(PAL,120,96);
// TV.select_font(font6x8);
Serial.begin(9600);
//mySerial.begin(9600);
setSyncProvider(RTC.get);
// if (timeStatus() != timeSet )
// Serial.println("Unable to sync with the RTC");
// else
// Serial.println("RTC has set the system time");
//tv.print(scan item) ???
//ITEM SCANNED GETS STORED INTO string.Readstring
//tv print (enter donation Amount)
//INPUT FROM KEYPAD GETS STORED INTO BUFFER1 (KEYPAD IS HOOKED UP TO SOFTWARE SERIAL PINS)
//THEN PRINTER PRINTS TITLE (MAYBE BETTER TO WAIT FOR ALL INPUT BEFORE PRINTING)
printer.justify('C');
//sets text justification (right, left, center) accepts 'L', 'C', 'R'
printer.setSize('L'); // set type size, accepts 'S', 'M', 'L'
printer.println("School Feast "); //print line
printer.setSize('M'); // set type size, accepts 'S', 'M', 'L'
printer.println("My Stall"); //print line
printer.println("My Town");
printer.feed(); //advance one line
printer.println(" My Country");
printer.feed(); //advance one line
}
void serialRead() {
while (Serial.available()) {
delay(10);
if (Serial.available() >0) {
char c = Serial.read();
readString += c;};
}
}
void loop() {
// THEN TIME GETS PRINTED
tmElements_t tm;
if (RTC.read(tm)) {
Serial.print(" ");
print2digits(tm.Hour);
Serial.write(':');
print2digits(tm.Minute);
Serial.write(':');
print2digits(tm.Second);
Serial.print(" ");
Serial.print(tm.Day);
Serial.write('/');
Serial.print(tm.Month);
Serial.write('/');
Serial.print(tmYearToCalendar(tm.Year));
Serial.println();
printer.print(" ");
print2digits(tm.Hour);
printer.write(':');
print2digits(tm.Minute);
printer.write(':');
print2digits(tm.Second);
printer.print(" ");
printer.print(tm.Day);
printer.write('/');
printer.print(tm.Month);
printer.write('/');
printer.print(tmYearToCalendar(tm.Year));
printer.println();
} else {
if (RTC.chipPresent()) {
Serial.println("The DS1307 is stopped. Please run the SetTime");
Serial.println("example to initialize the time and begin running.");
Serial.println();
} else {
Serial.println("DS1307 read error! Please check the circuitry.");
Serial.println();
}
delay(9000);
}
delay(1000);
}
void print2digits(int number) {
if (number >= 0 && number < 10) {
Serial.write('0');
}
Serial.print(number);
if (Serial.available() > 0) {
readString = "";
serialRead();
String Item = readString.substring(0,3);
//THEN ITEM PRINT( IDENTIFY ITEM BY FIRST 3 CHARACTERS OF STRING, HOW??)
Serial.print(Item);
printer.print(Item);
Serial.println();{
//THEN PRINT DONATION AMOUNT(INPUT FROM SOFTWARE SERIAL)
//printer.print(software.serial buffer)
//printer. print("GBP");
//clear display
//tv.clear
}
}
}

Related

Array Data Reading Failed

I am reading the data from a "Torque Wrench" using "USB Host Shield2.0" and Arduino UNO. I am receiving correct data from my "Torque Wrench" Data is receiving in a array.
But when I started reading data after "for" loop inside Void loop() I am receiving incorrect data. I attached Both output pictures correct and incorrect data.
Basically I am read data from Torque Wrench and send to receiver using Nrf24l01. I am receiving incorrect data.
My question is :- Why I am reading Incorrect data outside "for" loop.
Correct Data inside "for" loop :- enter image description here
Incorrect Data outside "for" loop :- enter image description here
#include <SPI.h> // for SPI communication
#include <nRF24L01.h>
#include <RF24.h>
#include <cdcacm.h>
#include <usbhub.h>
//#include "pgmstrings.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = {'R','x','A','A','A','B'}; // the address the the module
class ACMAsyncOper : public CDCAsyncOper
{
public:
uint8_t OnInit(ACM *pacm);
};
uint8_t ACMAsyncOper::OnInit(ACM *pacm)
{
uint8_t rcode;
// Set DTR = 1 RTS=1
rcode = pacm->SetControlLineState(3);
if (rcode)
{
ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
return rcode;
}
LINE_CODING lc;
lc.dwDTERate = 9600;
lc.bCharFormat = 0;
lc.bParityType = 0;
lc.bDataBits = 8;
rcode = pacm->SetLineCoding(&lc);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
return rcode;
}
USB Usb;
//USBHub Hub(&Usb);
ACMAsyncOper AsyncOper;
ACM Acm(&Usb, &AsyncOper);
void setup() {
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MAX);
radio.stopListening();
#if !defined(__MIPSEL__)
while (!Serial);
#endif
Serial.println("Start");
if (Usb.Init() == -1)
Serial.println("USB Not Connected");
delay( 200 );
}
void loop() {
Usb.Task();
if( Acm.isReady()) {
uint8_t rcode;
/* reading the keyboard */
if(Serial.available()) {
uint8_t data= Serial.read();
/* sending to the phone */
rcode = Acm.SndData(1, &data);
if (rcode)
ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
}
delay(10);
uint8_t buf[64];
uint16_t rcvd = 64;
char text[64];
rcode = Acm.RcvData(&rcvd, buf);
if (rcode && rcode != hrNAK)
ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
if ( rcvd ) {
for(uint16_t i=0; i < rcvd; i++ )
{
// Serial.print((char)buf[i]); // correct Data read from torque wrench
text[i] = (char)buf[i];
}
Serial.println(text); // reading wrong data here
//radio.write(&text, sizeof(text));
//Serial.println(text);
}
delay(10);
}
}
Character arrays must be null-terminated to count as C strings.
After the for loop, add text[rcvd] = '\0';
Also, your rcvd is fixed at 64. It needs to be one less than the array size for the null terminator to fit.

Granting access with RFID card

I've got a problem with my arduino program. I'm using a RFID reader to scan cards (this part works flawlessly). I want the program to grant access to using some buttons (doesn't matter to be honest). The user who uses a verified card can use the functionalities until he scans a card again. I've deleted some unnecessary parts of the code.
#include <SPI.h>
#include <MFRC522.h>
String read_rfid;
String ok_rfid_1="a3f90f7"; //ID of the verified CARD
const int buzzer=8; //Buzzer
const int redLed=7;
const int greenLed=6;
const int yellowLed=5;
byte access=false; //
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
}
/*
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
read_rfid="";
for (byte i = 0; i < bufferSize; i++) {
read_rfid=read_rfid + String(buffer[i], HEX);
}
}
void granted() { } //it lights up the green led
void denied() { } //it lights up the red led
void login() {
if (read_rfid==ok_rfid_1) {
granted();
access=true;
} else {
denied();
}
delay(1000);
}
void logout() {
if (read_rfid==ok_rfid_1 && access==1) {
access=false;
Serial.println("Logout ");
}
}
void loop() {
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println(read_rfid);
login();
while(access==true)
{logout();};
}
The logging in part works well, but it logs out automatically. As I observed the problem might be that if(read_rfid==ok_rfid_1 && access==1) is always true, because the read_rfid does not change. Do you have any ideas to solve my dillema?

Sending String from Processing to Arduino Not Working

I've collected some string information in processing and I am trying to send it to Arduino. I am getting processing to send the information, however, my output in arduino is weird. I get numbers like "77789...". I am not sure What I am doing wrong. All I need to do is, basically get a string from processing and send it to arduino to display it on a LCD screen.
Any help on this would be appreciated.
Here is my processing code:
import processing.serial.*;
Serial myPort;
XML MSFTxml; // loading Query
XML MSFT; // results of the query
XML row; // first row in the query
XML symbol; // Name of the stock
String symbolTxt;
String val;
void setup() {
size(200,200);
myPort = new Serial(this,"COM3", 9600);
}
void draw() {
updateXMLCall();
delay(10000);
}
void updateXMLCall () {
MSFTxml = loadXML("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%27http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes.csv%3Fs%3DMSFT%26f%3Dsl1d1t1c1ohgv%26e%3D.csv%27%20and%20columns%3D%27symbol%2Cprice%2Cdate%2Ctime%2Cchange%2Ccol1%2Chigh%2Clow%2Ccol2%27&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
MSFT = MSFTxml.getChild("results"); //Getting the first tag "results" in the query MSFT
row= MSFT.getChild("row"); //first child tag "row"
symbol = row.getChild("symbol"); //name of the stock
symbolTxt = symbol.getContent().toString(); //converting the name of the stock into a string
myPort.write(symbolTxt);
println(symbolTxt);
}
Here is my arduino Code:
#include <Wire.h>
#include "rgb_lcd.h"
rgb_lcd lcd;
const int colorR = 50;
const int colorG = 0;
const int colorB = 0;
void setup()
{
Serial.begin(9600);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
lcd.setRGB(colorR, colorG, colorB);
// Print a message to the LCD.
lcd.setCursor(0, 1);
}
void loop()
{
String content = "";
if (Serial.available()) {
while (Serial.available()) {
content += Serial.read();
lcd.print(content);
Serial.print(content);
lcd.setCursor(0, 1);
}
}
delay(100);
}
The problem is the use of += in C += doesn't concat strings.
You need to concatenate the char get from Serial.read() like here for example:
Convert serial.read() into a useable string using Arduino?

How to Sync an Arduino with a DS1307

I am using an Arduino and a DS1307. I have acquired the time from the RTC no problem but when i try to apply the setSyncProvider call i get a few errors which are implying to my ds1307.h files in my library. attached is my code and errors. These errors , I am not quite sure what they are and mean. Do I need to go in notepad++ and change lines 66-68 to something or alter the .h in anyway? Does any body have an idea? Your help is most appreciated. By the way, the code is from the Arduino Cookbook so i know it works, its just smething in that .h file...... i think
#include <Time.h>
#include <Wire.h>
#include <DS1307.h> // a basic DS1307 library that returns time as a time_t
void setup() {
Serial.begin(9600);
setSyncProvider(RTC.get); // the function to get the time from the RTC
if(timeStatus() != timeSet)
Serial.println("Unable to sync with the RTC");
else
Serial.println("RTC has set the system time");
}
void loop() {
if(Serial.available()) {
time_t t = processSyncMessage();
if(t > 0) {
RTC.set(t); // set the RTC and the system time to the received value
setTime(t);
}
}
digitalClockDisplay();
delay(1000);
}
void digitalClockDisplay() {
// digital clock display of the time
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.print(month());
Serial.print(" ");
Serial.print(year());
Serial.println();
}
// utility function for digital clock display: prints preceding colon and
// leading 0.
//
void printDigits(int digits) {
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
/* code to process time sync messages from the serial port */
#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by Unix time_t
#define TIME_HEADER 'T' // Header tag for serial time sync message
time_t processSyncMessage() {
while(Serial.available() >= TIME_MSG_LEN ) {
char c = Serial.read() ;
Serial.print(c);
if( c == TIME_HEADER ) {
time_t pctime = 0;
for(int i=0; i < TIME_MSG_LEN -1; i++) {
c = Serial.read();
if( c >= '0' && c <= '9') {
pctime = (10 * pctime) + (c - '0') ; // convert digits to a number
}
}
return pctime;
}
}
return 0;
}
My errors.......................................
sketch_dec27d.ino: In function 'void setup()':
sketch_dec27d:14: error: no matches converting function 'get' to type 'time_t (*)()'
C:\Users\AlbertR\Desktop\arduino-1.0.3\libraries\DS1307/DS1307.h:66: error: candidates are: void DS1307::get(int*, boolean)
C:\Users\AlbertR\Desktop\arduino-1.0.3\libraries\DS1307/DS1307.h:67: error: int DS1307::get(int, boolean)
sketch_dec27d.ino: In function 'void loop()':
sketch_dec27d:27: error: no matching function for call to 'DS1307::set(time_t&)'
C:\Users\AlbertR\Desktop\arduino-1.0.3\libraries\DS1307/DS1307.h:68: note: candidates are: void DS1307::set(int, int)

Parse the incoming packet

I am receiving a packet like 0xFA5D0D01.
Now i want to parce it like
FA is Header1
5D is Header2
0D is length and
01 is checksum.
const int data_availabe = Serial.available();
I am able to write to serial port but not able to parce it like
if i received FA is then print received Header1
const int data_availabe = Serial.available();
if (data_availabe <= 0)
{
return;
}
const int c = Serial.read();
Serial.print("Receive Status: ");
Serial.println(STATE_NAME[receiveState]);
Serial.print(c, HEX);
Serial.print(" ");
if (isprint(c)) //isprint checks whether it is printable character or not (e.g non printable char = \t)
{
Serial.write(c);
}
Serial.println();
Serial.println(receiveState);
switch (receiveState)
{
case WAITING_FOR_HEADER1:
if (c == HEADER1)
{
receiveState = WAITING_FOR_HEADER2;
}
break;
case WAITING_FOR_HEADER2:
if (c == HEADER2)
{
receiveState = WAITING_FOR_LENGTH;
}
break;
}
Where receiveState is enum changing as we are getting exptected data..
I assume the Arduino is receiving data from USB.
What is the if (data available <= 0) doing? If you want want to read data from the serial port while it is avalaible, you should better do if (Serial.avalaible() > 1) and then Serial.read() inside the {}.
If you initialize a const you won't be able to change its value over time...
What is readString and how is it initialized?
Have you tried to Serial.print(c) to see what's inside?
Once again, it would be easier for us if you could give us more context on why and when this piece of code is running.
EDIT:
#define HEADER_1 0xFA // here you define your headers, etc. You can also use variables.
uint8_t readByte[4]; // your packet is 4 bytes long. each byte is stored in this array.
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.avalaible() > 1) { // when there is data avalaible on the serial port
readByte[0] = Serial.read(); // we store the first incomming byte.
delay(10);
if (readByte[0] == HEADER_1) { // and check if that byte is equal to HEADER_1
for (uint8_t i = 1 ; i < 4 ; i++) { // if so we store the 3 last bytes into the array
readByte[i] = Serial.read();
delay(10);
}
}
}
//then you can do what you want with readByte[]... i.e. check if readByte[1] is equal to HEADER_2 and so on :)
}

Resources