How to initialize a DT028ATFT display - c

I am trying to initialize a DT028ATFT-TS display on an STM32F10B main board. The system worked with DT028TFT-TS before, but that display has been discontinued. As a result of using the new diplay, the interface also had to change from ILI9320 to ILI9341. I am now basically trying to initialize the new display in a configuration that would be equivalent to what I had before.
The problem I am facing is that the display image ends up showing horizontal streaks randomly distributed (slightly different at every startup) with a bit of a flicker. And, at times (not sure if related), it just shows the backlight and nothing else - no streaks, no test image. The test image is just one big red square (100x100) displayed at x=100, y=50. You can see the effect of the problem here: Streaked Display Image.
The following is part of the initialization code that I've used - part of it taken as such from DisplayTech's sample code offered on their website, part of it customized. I've excluded commands from the sample code that are not documented under ILI9341 (probably vendor customization) and the gamma correction parameters, just to save some space. Any help in finding out where I went wrong would be appreciated.
// DT028ATFT LCD init - ILI9341:
// Frame Rate Control
SPI_WriteCMD(0xB1);
SPI_WriteDAT(0x00); // division ratio: 1
SPI_WriteDAT(0x10); // 16 clocks per line
// Power Control
SPI_WriteCMD(0xC0);
SPI_WriteDAT(0x25); // GVDD = 4.70V
SPI_WriteCMD(0xC1);
SPI_WriteDAT(0x03); // VCL=VCI x 2, VGH=VCI x 6, VGL=-VCI x 3
// VCOM Control
SPI_WriteCMD(0xC5);
SPI_WriteDAT(0x5C); // VCOMH = 5.000 V
SPI_WriteDAT(0x4C); // VCOML = -0.600 V
SPI_WriteCMD(0xC7);
SPI_WriteDAT(0x94); // VCOMH = VMH - 44, VCOML = VML - 44
// Memory Access Control
SPI_WriteCMD(0x36);
SPI_WriteDAT(0x08); // BGR=1, Normal addr order and refresh direction
// Write CTRL Display
SPI_WriteCMD(0x53);
SPI_WriteDAT(0x24); // BCTRL=1, DD=0, BL=1
// Display Function Control
SPI_WriteCMD(0xB6);
SPI_WriteDAT(0x00); // Normal scan, V63 pos pol / V0 neg pol
SPI_WriteDAT(0xA0); // LCD normally white, G1 to G320, S720 to S1
SPI_WriteDAT(0x27); // NL = 320
SPI_WriteDAT(0x00); // PCDIV not used
// Entry Mode Set
SPI_WriteCMD(0xB7);
SPI_WriteDAT(0x06); // Normal display for G1-G320 output, Low voltage detection enabled
// Column Address Set
SPI_WriteCMD(0x2A);
SPI_WriteDAT(0x00);
SPI_WriteDAT(0x00); // Start Column = 0
SPI_WriteDAT(0x00);
SPI_WriteDAT(0xEF); // End Column = 239
// Page Address Set
SPI_WriteCMD(0x2B);
SPI_WriteDAT(0x00);
SPI_WriteDAT(0x00); // Start Page = 0
SPI_WriteDAT(0x01);
SPI_WriteDAT(0x3F); // End Page = 319
// Gamma Set
SPI_WriteCMD(0x26);
SPI_WriteDAT(0x01); // Gamma Curve 1 selected (G2.2)
// Pixel Format Set
SPI_WriteCMD(0x3A);
SPI_WriteDAT(0x55); // 16bits/pixel (RGB and MCU i/f)
// Interface Control
SPI_WriteCMD(0xF6);
SPI_WriteDAT(0x00); // image data not wrapped around (exceeding data ignored)
SPI_WriteDAT(0x00); // MSB used also as LSB for R and B (64k colours)
SPI_WriteDAT(0x00); // Disp Op Mode: internal clk, GRAM access: Sys I/F, 1 transf/pxl (16bit 64k colours)
// RGB Interface Signal Control
SPI_WriteCMD(0xB0);
SPI_WriteDAT(0xC0); // BypassMode=1, RCM=2, VSPL=0, HSPL=0, DPL=0, EPL=0
// Sleep Mode off (DC/DC conv enabled, internal osc started)
SPI_WriteCMD(0x11);
Dly100us((void*)1200);
// Display ON
SPI_WriteCMD(0x29);
// ===============================

your problem sounds like a timing issue. Have you tried reducing the frame rate? that should relax the display timing. you are setting it to 119 Hz.
are you doing a proper reset before the init?
you can compare with other implementations for the ILI9341 controller:
Example
Atmel Library

Related

Vulkan swapchain creation causes crash with no debug information

I'm following vulkan-tutorial's procedure to understand vulkan, I'm now in creating swapchain. before that I've also created instance and a debug/validation layer but when I'm trying to create swapchain, the app crashes.
void createSwapChain() {
VkSurfaceFormatKHR surfaceFormat;
surfaceFormat.format=VK_FORMAT_B8G8R8A8_SRGB;
surfaceFormat.colorSpace=VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
VkPresentModeKHR presentMode=VK_PRESENT_MODE_FIFO_KHR;
int width,height;
glfwGetFramebufferSize(window, &width, &height);
VkExtent2D extent ={width,height};
uint32_t imageCount=2;//minimum cap +1
VkSurfaceCapabilitiesKHR capabilities;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &capabilities);
VkSwapchainCreateInfoKHR createInfo={0};
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = surface;
createInfo.minImageCount = imageCount;
createInfo.imageFormat = surfaceFormat.format;
createInfo.imageColorSpace = surfaceFormat.colorSpace;
createInfo.imageExtent = extent;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
// createInfo.queueFamilyIndexCount = 1;
// createInfo.pQueueFamilyIndices = NULL;
createInfo.preTransform = capabilities.currentTransform/*VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR*/;//swapChainSupport.capabilities.currentTransform
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = presentMode;
createInfo.clipped = VK_TRUE;// means obscured images have unimportant color!!
createInfo.oldSwapchain = VK_NULL_HANDLE;
if (vkCreateSwapchainKHR(device, &createInfo, NULL, &swapChain) != VK_SUCCESS)
printf("failed to create swap chain!");
}
Is there any idea? The host is eclipse with MinGW-64 -lglfw3 and -lvulkan-1 on windows 10 64-bit.
And here the graphic card information:
Available Layers:
VK_LAYER_AMD_switchable_graphics
VK_LAYER_VALVE_steam_overlay
VK_LAYER_VALVE_steam_fossilize
VK_LAYER_KHRONOS_validation
Available extensions:
VK_KHR_device_group_creation
VK_KHR_external_fence_capabilities
VK_KHR_external_memory_capabilities
VK_KHR_external_semaphore_capabilities
VK_KHR_get_physical_device_properties2
VK_KHR_get_surface_capabilities2
VK_KHR_surface
VK_KHR_win32_surface
VK_EXT_debug_report
VK_EXT_debug_utils
VK_EXT_swapchain_colorspace
Instance extension:
VK_KHR_surface
VK_KHR_win32_surface
VK_EXT_debug_utils
Availible devices:
AMD Radeon(TM) Graphics Type: 1 GeometryShader: Yes
FamilyIndex: 0 AvailibleQueueCount: 1 Surface Support: Yes Graphics | Compute | Transfer | Binding
FamilyIndex: 1 AvailibleQueueCount: 2 Surface Support: Yes | Compute | Transfer | Binding
FamilyIndex: 2 AvailibleQueueCount: 1 Surface Support: Yes | | Transfer | Binding
Availible device extensions: (The required is VK_KHR_swapchain)
VK_KHR_16bit_storage VK_KHR_8bit_storage VK_KHR_bind_memory2
VK_KHR_buffer_device_address VK_KHR_copy_commands2 VK_KHR_create_renderpass2
VK_KHR_dedicated_allocation VK_KHR_depth_stencil_resolve VK_KHR_descriptor_update_template
VK_KHR_device_group VK_KHR_draw_indirect_count VK_KHR_driver_properties
VK_KHR_dynamic_rendering VK_KHR_external_fence VK_KHR_external_fence_win32
VK_KHR_external_memory VK_KHR_external_memory_win32 VK_KHR_external_semaphore
VK_KHR_external_semaphore_win32 VK_KHR_format_feature_flags2 VK_KHR_get_memory_requirements2
VK_KHR_global_priority VK_KHR_imageless_framebuffer VK_KHR_image_format_list
VK_KHR_maintenance1 VK_KHR_maintenance2 VK_KHR_maintenance3
VK_KHR_maintenance4 VK_KHR_multiview VK_KHR_pipeline_executable_properties
VK_KHR_pipeline_library VK_KHR_push_descriptor VK_KHR_relaxed_block_layout
VK_KHR_sampler_mirror_clamp_to_edge VK_KHR_sampler_ycbcr_conversion VK_KHR_separate_depth_stencil_layouts
VK_KHR_shader_atomic_int64 VK_KHR_shader_clock VK_KHR_shader_draw_parameters
VK_KHR_shader_float16_int8 VK_KHR_shader_float_controls VK_KHR_shader_integer_dot_product
VK_KHR_shader_non_semantic_info VK_KHR_shader_subgroup_extended_types VK_KHR_shader_subgroup_uniform_control_flow
VK_KHR_shader_terminate_invocation VK_KHR_spirv_1_4 VK_KHR_storage_buffer_storage_class
Swap chain details:
Min/max images in swap chain; 1, 16
Min/max width and height 800 : 600 | 800 : 600
Pixel format codes(at least we need one no matter what!): 44
50 58 97 44 50 58 97 58 97 58
97 97 2 3 4 5 8 37 38 43
45 51 52 57 64 91 92 122
color space codes(at least we need one no matter what!): 0
0 0 0 1000104006 1000104006 1000104006 1000104006 1000104008 1000104008 1000104007
1000104007 1000104002 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
Available presentation modes:
0 (Immediate)
2 3 ( FIFO, FIFO_relaxed)
A few things:
There isn't really enough information in the problem description to allow others to locate the problem. For example, we can't tell how surface got created and we can't tell how the Vulkan device got created. It is better to post a complete reproducible example someplace and point to it.
There are a lot of hits when searching for "vulkan swapchain exception" like this one and this one. Something there may give a clue.
Based on what is provided and the links mentioned above, my best guess is that you're not enabling the swapchain extension when creating the device. Perhaps you could check that?
The validation layer should be helpful and you can find more information about it here. You might try making a vk_layer_settings.txt file and use it to set the message severity to "info" so that you can verify that the layer is active. (It will print some sort of startup message at this level) Your IDE might be swallowing the text output coming from the validation layer and the point behind doing this is to verify that you can see any validation output. It may be easier to provide a log filename in the same settings file to send the validation output to that file instead of figuring out what the IDE is doing. You can also use the vkconfig tool to apply these sorts of settings to the validation layer.

How do i record JANUS signal as wav file?

I am testing an interoperability between modems. one of my modem did support JANUS and I believe UnetStack base Subnero Modem Phy[3] also support JANUS. How can i send and record JANUS signal which i can use for preliminary testing for other modem ? Can someone please provide basic snippet ?
UnetStack indeed has an implementation of JANUS that is, by default, configured on phy[3].
You can check this on your modem (the sample outputs here are from unet audio SDOAM, and so your modem parameters might vary somewhat):
> phy[3]
« PHY »
[org.arl.unet.phy.PhysicalChannelParam]
fec = 7
fecList ⤇ [LDPC1, LDPC2, LDPC3, LDPC4, LDPC5, LDPC6, ICONV2]
frameDuration ⤇ 1.1
frameLength = 8
janus = true
[org.arl.yoda.FhbfskParam]
chiplen = 1
fmin = 9520.0
fstep = 160.0
hops = 13
scrambler = 0
sync = true
tukey = true
[org.arl.yoda.ModemChannelParam]
modulation = fhbfsk
preamble = (2400 samples)
threshold = 0.0
(I have dropped a few parameters that are not relevant to the discussion here to keep the output concise)
The key parameters to take note of:
modulation = fhbfsk and janus = true setup the modulation for JANUS
fmin = 9520.0, fstep = 160.0 and hops = 13 are the modulation parameters to setup fhbfsk as required by JANUS
fec = 7 chooses ICONV2 from the fecList, as required by JANUS
threshold = 0.0 indicates that reception of JANUS frames is disabled
NOTE: If your modem is a Subnero M25 series, the standard JANUS band is out of the modem's ~20-30 kHz operating band. In that case, the JANUS scheme is auto-configured to a higher frequency (which you will see as fmin in your modem). Do note that this frequency is important to match for interop with any other modem that might support JANUS at a higher frequency band.
To enable JANUS reception, you need to:
phy[3].threshold = 0.3
To avoid any other detections from CONTROL and DATA packets, we might want to disable those:
phy[1].threshold = 0
phy[2].threshold = 0
At this point, you could make a transmission by typing phy << new TxJanusFrameReq() and put a hydrophone next to the modem to record the transmitted signal as a wav file.
However, I'm assuming you would prefer to record on the modem itself, rather than with an external hydrophone. To do that, you can enable the loopback mode on the modem, and set up the modem to record the received signal:
phy.loopback = true # enable loopback
phy.fullduplex = true # enable full duplex so we can record while transmitting
phy[3].basebandRx = true # enable capture of received baseband signal
subscribe phy # show notifications from phy on shell
Now if you do a transmission, you should see a RxBasebandSignalNtf with the captured signal:
> phy << new TxJanusFrameReq()
AGREE
phy >> RxFrameStartNtf:INFORM[type:#3 rxTime:492455709 rxDuration:1100000 detector:0.96]
phy >> TxFrameNtf:INFORM[type:#3 txTime:492456016]
phy >> RxJanusFrameNtf:INFORM[type:#3 classUserID:0 appType:0 appData:0 mobility:false canForward:true txRxFlag:true rxTime:492455708 rssi:-44.2 cfo:0.0]
phy >> RxBasebandSignalNtf:INFORM[adc:1 rxTime:492455708 rssi:-44.2 preamble:3 fc:12000.0 fs:12000.0 (13200 baseband samples)]
That notification has your signal in baseband complex format. You can save it to a file:
save 'x.txt', ntf.signal, 2
To convert to a wav file, you'll need to load this signal and convert to passband. Here's some example Python code to do this:
import numpy as np
import scipy.io.wavfile as wav
import arlpy.signal as asig
x = np.genfromtxt('x.txt', delimiter=',')
x = x[:,0] + 1j * x[:,1]
x = asig.bb2pb(x, 12000, 12000, 96000)
wav.write('x.wav', 96000, x)
NOTE: You will need to replace the fd and fc of 12000 respectively, by whatever is the fs and fc fields in your modem's RxBasebandSignalNtf. For Unet audio, it is 12000 for both, but for Subnero M25 series modems it is probably 24000.
Now you have your wav file at 96 kSa/s!
You could also plot a spectrogram to check if you wanted to:
import arlpy.plot as plt
plt.specgram(x, fs=96000)
I have an issue while recording the signal. Modem refuse to send the JANUS frame. It looks like something is not correctly set on my end, specially fmin = 12000.0 , fstep = 160.0 and hops = 13. The Actual modem won't let me set the fmin to 9520.0 and automatically configured on lowest fmin = 12000. How can i calculate corresponding parameters for fmin=12000.
Although your suggestion do work on the unet audio.
Here is my modem logs:
> phy[3]
« PHY »
[org.arl.unet.DatagramParam]
MTU ⤇ 0
RTU ⤇ 0
[org.arl.unet.phy.PhysicalChannelParam]
dataRate ⤇ 64.0
errorDetection ⤇ true
fec = 7
fecList ⤇ [LDPC1, LDPC2, LDPC3, LDPC4, LDPC5, LDPC6, ICONV2]
frameDuration ⤇ 1.0
frameLength = 8
janus = true
llr = false
maxFrameLength ⤇ 56
powerLevel = -10.0
[org.arl.yoda.FhbfskParam]
chiplen = 1
fmin = 12000.0
fstep = 160.0
hops = 13
scrambler = 0
sync = true
tukey = true
[org.arl.yoda.ModemChannelParam]
basebandExtra = 0
basebandRx = true
modulation = fhbfsk
preamble = (2400 samples)
test = false
threshold = 0.3
valid ⤇ false
> phy << new TxJanusFrameReq()
REFUSE: Frame type not setup correctly
phy >> FAILURE: Timed out

how to receive data from mqtt and open cv video stream at the same time

My project need to receive mqtt data and videostream data at the same time. However, when my raspi receiving video data by open cv, it cant receive iOT data at the same time.
My raspi need to check if the iot data is on, and the video will not turn on and receive data.
So the piority is
iOT sensor check if there is something detected-----> video will not turn. (case 1)
iOT sensor check if there is nothing detected-------> video turn on and receive another image data.
[Update 2]
# import the necessary packages
from collections import deque
from imutils.video import VideoStream
import numpy as np
import argparse
import cv2
import imutils
import time
import serial
import struct
import paho.mqtt.client as mqtt
#subscribe mqtt publisher with topic "esp/pot"
def on_connect(client, userdata,flags, rc):
client.subscribe("/esp/pot")
#get the data from the publisher and save to integer variable "bdy"
def on_message(client, userdata, msg):
bdy=int(msg.payload)
#when disconnect stop the loop of mqtt function
def on_disconnect(client, userdata,rc=0):
client.loop_stop()
#Assign the mqtt client as client
client = mqtt.Client()
#Assign the mqtt connect function to client connect
client.on_connect = on_connect
#Assign the mqtt message function to client message
client.on_message = on_message
#set the client connect to local broker host
client.connect("localhost", 1883, 60) # localhost is the Raspberry Pi itself
#Below is setting up the OpenCV function
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
#get the video if path provided
ap.add_argument("-v", "--video",
help="path to the (optional) video file")
ap.add_argument("-b", "--buffer", type=int, default=0,
help="max buffer size")
args = vars(ap.parse_args())
# define detect object, in here is a green object
# define the lower and upper boundaries of the "green" color in HSV value
# ball in the HSV colorspace, then initialize the
# list of tracked points
greenLower = (25, 96, 49)
greenUpper = (39, 255, 255)
Lower = greenLower
Upper = greenUpper
#define the trace point of the object detected, here is centroid
pts = deque(maxlen=args["buffer"])
#setup the serial port for arduino, which is for another motor control
ser = serial.Serial('/dev/ttyUSB0',9600)
# if a video path was not supplied, grab the reference
# to the webcam (we use webcam in this project
if not args.get("video", False):
vs = VideoStream(src=0).start()
# otherwise, grab a reference to the video file
else:
vs = cv2.VideoCapture(args["video"])
# allow the camera or video file to warm up
time.sleep(2.0)
#initialize the integer variable "bdy" to zero
bdy = 0
# main function body, keep looping
while True:
# grab the current frame of the webcam
frame = vs.read()
# handle the frame from VideoCapture or VideoStream
frame = frame[1] if args.get("video", False) else frame
# if we are viewing a video and we did not grab a frame,
# then we have reached the end of the video
if frame is None:
break
# resize the frame, blur it, and convert it to the HSV
# color space
frame = imutils.resize(frame, width=246)
blurred = cv2.GaussianBlur(frame, (11, 11), 0)
hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
# construct a mask for the color "green", then perform
# a series of dilations and erosions to remove any small
# blobs left in the mask
mask = cv2.inRange(hsv, Lower, Upper)
mask = cv2.erode(mask, None, iterations=2)
mask = cv2.dilate(mask, None, iterations=2)
# find contours in the mask and initialize the current
# (x, y) center of the green object
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
#initial center value
center = None
#start mqtt client loop function for receiving data from broker, int variable "bdy"
client.loop_start()
#if the data from broker is not 1
if bdy != 1:
#printout bdy value for debug
print (bdy)
# only proceed if at least one contour of green object was found
if len(cnts) > 0:
# find the largest contour in the mask, then use
# it to compute the minimum enclosing circle and
# centroid
c = max(cnts, key=cv2.contourArea)
#save webcam detected object centroid to cX and cY
((x, y), radius) = cv2.minEnclosingCircle(c)
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
#locate the centre of the green object
center = (cX, cY)
# only proceed if the radius of the detected green object meets a minimum size,
# say radius >2 to remove unneccssary noise
if radius > 2:
# draw the circle and centroid on the frame,
# then update the list of tracked points
#cv2.circle(frame, (int(x), int(y)), int(radius),
#(0, 255, 255), 2)
cv2.circle(frame, center, 5, (0, 0, 255), -1)
# print x_position
print (cX)
# send the cX value to the arduino by serial port with braud rate 9600
ser.write(struct.pack('>H', cX))
# if the data from broker is not 1,
# here the broker actually just send data from sensor with digital value
# so it should be 0
else:
print("boundary detected")
#stop the client loop function from receive data for clearing the retain messsage
client.loop_stop()
# show the frame from webcam to raspberry pi screen for debug
cv2.imshow("Frame", frame)
#awaiting user press key for action
chkKey = cv2.waitKey(1) & 0xFF
# if the 'q' key is pressed, stop the main function body "while True loop"
if chkKey == ord("q"):
break
# if we are not using a video file, stop the camera video stream
if not args.get("video", False):
vs.stop()
# otherwise, release the camera
else:
vs.release()
# close all windows
cv2.destroyAllWindows()
#stop the client loop function
client.loop_stop()

Verilog - digital clock- Minute doesnt work

im implementing a digital clock with verilog. I count clk's and so count seconds. Then i sent outputs to seven segment display. My second display works perfectly, but minute's doesnt work . Some times , it displays like , in first increase 60, in second 2 , third 45 60 anything, fourth 4.
I created split module which takes 1 input give 2 output. Like
if input = 56 , output 1 = 5 , output 2=6 . Works perfect in simulation and for second.
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 23:36:40 11/05/2015
// Design Name:
// Module Name: Top
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Top(input clk,reset,input in0, in1, in2, in3,output a, b, c, d, e, f, g, dp,output [3:0] an
);
wire [3:0] minLeft,minRight;
wire [3:0] secLeft,secRight;
wire [6:0] second,minute;
wire[4:0] hour;
wire newDay;
split_output sec(second,secLeft,secRight);
split_output split(minute,minLeft,minRight);
Clock timer(clk,second,minute,hour,newDay);
sevenseg decoder(clk,reset,minLeft,minRight,secLeft,secRight,a,b,c,d,e,f,g,dp,an);
endmodule
CLOCK MODULE
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 21:26:35 11/05/2015
// Design Name:
// Module Name: Clock
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module Clock(input clk,output [6:0] second,minute,output [4:0] hour,output reg newDay
);
//Clock counter for second
reg [25:0]cnt_clk=0;
//Second counter
reg [6:0]cnt_second=0;
//Minutes counter
reg [6:0]cnt_minute=0;
//Hour counter
reg [4:0]cnt_hour=0;
assign second=cnt_second;
assign minute=cnt_minute;
assign hour=cnt_hour;
//COUNT CLOCK, INCREASE SECOND
always#(*)
begin
// IF CLOCK COUNT İS 1 SECOND
if(cnt_clk==26'd5000000)
begin
cnt_clk=26'd0;
// IF SECOND COUNT İS 60, RESET İT
if(cnt_second==7'b0111100)
begin
cnt_second<=7'b0000000;
end
else
begin
cnt_second<=cnt_second+1;
end
end
else
begin
cnt_clk=cnt_clk+1;
end
end
// UPDATE MİNUTES, AS SECONDS INCREASE
always#(cnt_second)
begin
//IF ITS 1 MINUTES
if(cnt_second==7'd60)
begin
if(cnt_minute==7'd60)
begin
cnt_minute<=0;
end
else
begin
cnt_minute=cnt_minute+1;
end
end
end
//UPDATE HOURS,AS MİNUTES INCREASE
always#(cnt_minute)
begin
//IF ITS 60 MINUTES
if(cnt_minute==7'b0111100)
begin
if(cnt_hour==5'b11000)
begin
cnt_hour<=5'b00000;
end
else
begin
cnt_hour<=cnt_hour+1;
end
end
end
// IF THE DAY İS OVER
always#(cnt_hour)
begin
if(cnt_hour==5'b11000)
begin
newDay=1;
end
else
begin
newDay=0;
end
end
endmodule
SPLİT MODULE
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 18:51:22 11/09/2015
// Design Name:
// Module Name: split_output
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module split_output(input [7:0] total,output reg[3:0] left,right
);
always#(total)
begin
if(total>=8'b00110010&&total<8'b00111100)
begin
assign left=4'b0101;
assign right=total-50;
end
if(total>=8'b00101000&&total<8'b00110010)
begin
assign left=4'b0100;
assign right=total-40;
end
if(total>=8'b00011110&&total<8'b00101000)
begin
assign left=4'b0011;
assign right=total-30;
end
if(total>=8'b00010100&&total<8'b00011110)
begin
assign left=4'b0010;
assign right=total-20;
end
if(total>=8'b00001010&&total<8'b00010100)
begin
assign left=4'b0001;
assign right=total-10;
end
if(total<8'b00001010)
begin
assign left=0;
assign right=total;
end
if(total==8'b00111100)
begin
assign left=4'b0110;
assign right=0;
end
end
endmodule
7seg decoder- i found in that site- it works perfect( THANKS TO WHO PUBLİSHED AGAİN)
`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 23:31:47 11/05/2015
// Design Name:
// Module Name: sevenseg
// Project Name:
// Target Devices:
// Tool versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////
module sevenseg(
input clock, reset,
input [3:0] in0, in1, in2, in3, //the 4 inputs for each display
output a, b, c, d, e, f, g, dp, //the individual LED output for the seven segment along with the digital point
output [3:0] an // the 4 bit enable signal
);
localparam N = 18;
reg [N-1:0]count; //the 18 bit counter which allows us to multiplex at 1000Hz
always # (posedge clock or posedge reset)
begin
if (reset)
count <= 0;
else
count <= count + 1;
end
reg [6:0]sseg; //the 7 bit register to hold the data to output
reg [3:0]an_temp; //register for the 4 bit enable
always # (*)
begin
case(count[N-1:N-2]) //using only the 2 MSB's of the counter
2'b00 : //When the 2 MSB's are 00 enable the fourth display
begin
sseg = in0;
an_temp = 4'b1110;
end
2'b01: //When the 2 MSB's are 01 enable the third display
begin
sseg = in1;
an_temp = 4'b1101;
end
2'b10: //When the 2 MSB's are 10 enable the second display
begin
sseg = in2;
an_temp = 4'b1011;
end
2'b11: //When the 2 MSB's are 11 enable the first display
begin
sseg = in3;
an_temp = 4'b0111;
end
endcase
end
assign an = an_temp;
reg [6:0] sseg_temp; // 7 bit register to hold the binary value of each input given
always # (*)
begin
case(sseg)
4'd0 : sseg_temp = 7'b1000000; //to display 0
4'd1 : sseg_temp = 7'b1111001; //to display 1
4'd2 : sseg_temp = 7'b0100100; //to display 2
4'd3 : sseg_temp = 7'b0110000; //to display 3
4'd4 : sseg_temp = 7'b0011001; //to display 4
4'd5 : sseg_temp = 7'b0010010; //to display 5
4'd6 : sseg_temp = 7'b0000010; //to display 6
4'd7 : sseg_temp = 7'b1111000; //to display 7
4'd8 : sseg_temp = 7'b0000000; //to display 8
4'd9 : sseg_temp = 7'b0010000; //to display 9
default : sseg_temp = 7'b0111111; //dash
endcase
end
assign {g, f, e, d, c, b, a} = sseg_temp; //concatenate the outputs to the register, this is just a more neat way of doing this.
// I could have done in the case statement: 4'd0 : {g, f, e, d, c, b, a} = 7'b1000000;
// its the same thing.. write however you like it
assign dp = 1'b1; //since the decimal point is not needed, all 4 of them are turned off
endmodule
MY UCF
NET "reset" LOC = "a7";
# Pin assignment for 7-segment displays
NET "a" LOC = "l14" ;
NET "b" LOC = "h12" ;
NET "c" LOC = "n14" ;
NET "d" LOC = "n11" ;
NET "e" LOC = "p12" ;
NET "f" LOC = "l13" ;
NET "g" LOC = "m12" ;
NET "dp" LOC = "n13" ;
NET "an[0]" LOC = "k14";
NET "an[1]" LOC = "m13";
NET "an[2]" LOC = "j12";
NET "an[3]" LOC = "f12";
# Pin assignment for clock
NET "clk" LOC = "b8";
Blocking (=) vs non-blocking (<=) been answered may times:
How to interpret blocking vs non blocking assignments in Verilog?
Verilog Blocking Assignment
Nonblocking Assignments in Verilog Synthesis, Coding
Styles That Kill! (Cliff Cummings paper)
Latches are inferred when a reg is not assigned in all possible branches within a otherwise conbinational block. If you want latches, put them in a separate always block, away from the combinational logic, use non-blocking (<=) assignments, and keep them as simple assignments. Doing so will remove the confusion of what is intended to be decoding logic, level sensitive latches, and edge sensitive flip-flops. Combinational loops are another hazard. This is where you get different results if you run the same combinational block two or more times with the same inputs in the same time stamp and get different outputs.
When it comes to RTL coding style, I typically follow Cliff Cummings' recommendations, such as:
The Fundamentals of Efficient Synthesizable Finite State Machine
Design
Coding And Scripting Techniques For FSM Designs With
Synthesis-Optimized, Glitch-Free Outputs
There are additional links to useful Verilog/SystemVerilog references in my profile. I personally do not like nested conditional statements (?:). From experience, I get better synthesis results using case statements when there are more then two possibilities.
Here is an incomplete example how I would code Clock and split_output. I'll leave the rest for you figure out and learn on your own.
module Clock(
input clk,
output reg [5:0] second, minute,
output reg [3:0] hour,
output reg newDay
);
// ... declare local regs
// SYNCHRONOUS ASSIGNMENTS
always #(posedge clk) begin
cnt_clk <= next_cnt_clk;
second <= next_second;
// ... other assignments
end
// COMBINATIONAL CALCULATIONS
always #* begin
// DEFAULT VALUES
next_cnt_clk = cnt_clk + 1;
next_second = second;
// ... other default
// IF CLOCK COUNT İS 1 SECOND
if (next_cnt_clk == 24'd5000000) begin
next_cnt_clk = 24'd0;
next_second = second + 1;
end
// IF SECOND COUNT İS 60, RESET İT
if (next_second == 6'd60) begin
next_second = 6'd0;
next_minute = minute + 1;
end
// ... other calculations
end
endmodule
module split_output(
input [5:0] total,
output reg [3:0] left, right
);
always #* begin
if (total < 8'd10) begin
left = 4'b0000;
right = total[3:0];
end
else if (total < 8'd20) begin
left = 4'b0001;
right = total-10;
end
// ... other 'else if'
else begin // final is 'else'
left = 4'b0110;
right = 4'b0000;
end
end
endmodule

Conversion of MetaTrader4 to NinjaTrader

I am trying to write an indicator originally from MT4 into NT7.
I have the following calculations in MT4:
dayi = iBarShift(Symbol(), myPeriod, Time[i], false);
Q = (iHigh(Symbol(), myPeriod,dayi+1) - iLow(Symbol(),myPeriod,dayi+1));
L = iLow(NULL,myPeriod,dayi+1);
H = iHigh(NULL,myPeriod,dayi+1);
O = iOpen(NULL,myPeriod,dayi+1);
C = iClose(NULL,myPeriod,dayi+1);
myperiod is a variable where I place the period in minutes (1440 = 1day).
What are the equivalent functions in NT7 to iBarShift, iHigh and so on?
Thanks in advance
For NinjaTrader:
iLow = Low or Lows for multi-time frame
iHigh = High or Highs
iOpen = Open or Opens
iClose = Close or Closes
So an example would be
double low = Low[0]; // Gets the low of the bar at index 0, or the last fully formed bar (If CalculateOnBarClose = true)
In order to make sure you are working on the 1440 minute time frame, you will need to add the following in the Initialize() method:
Add(PeriodType.Minute, 1440);
If there are no Add statements prior to this one, it will place it at index 1 (O being the chart default index) in a 2 dimensional array. So to access the low of the 1440 minute bar at index 0 would be:
double low = Lows[1][0];
For iBarShift look at
int barIndex = Bars.GetBar(time);
which will give you the index of the bar with the matching time. If you need to use this function on the 1440 bars (or other ones), use the BarsArray property to access the correct Bar object and then use the GetBar method on it. For example:
int barIndex = BarsArray[1].GetBar(time);
Hope that helps.

Resources